Created
July 27, 2016 15:03
-
-
Save davidism/645100dc43633c02d60f156ef4d0d451 to your computer and use it in GitHub Desktop.
class namespace scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = 'global' | |
class Fred: | |
a = 'class' | |
b = (a for i in range(10)) | |
c = [a for i in range(10)] | |
d = a | |
e = lambda: a | |
f = lambda a=a: a | |
@staticmethod | |
def g(): | |
return a | |
print(Fred.a) # class | |
print(next(Fred.b)) # global | |
print(Fred.c[0]) # class in Python 2, global in Python 3 | |
print(Fred.d) # class | |
print(Fred.e()) # global | |
print(Fred.f()) # class | |
print(Fred.g()) # global |
The results should be less surprising the further down you go. Comprehensions are the most surprising, but they're basically implemented as functions. Lambdas are functions, and by the time you get to the static (or class, or instance) method this should look completly normal. Functions / methods don't use the class namespace for name lookup.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Discussed on sopython: http://chat.stackoverflow.com/transcript/message/31960971#31960971
Explanation on python-dev found here: http://chat.stackoverflow.com/transcript/message/31961453#31961453
https://mail.python.org/pipermail/python-dev/2009-February/086288.html