The basic principle is to scope everything as tightly as possible without introducing any 'garbage' (extra types/functions) into a wider scope than is absolutely required - Nothing else wants to use the do_first_thing() method for example so it shouldn't be scoped outside the calling function.
>>> x = 'OLD'
>>> sample = [x for x in 'NEW']
>>> x
'W'
But in Python 3, even though the variable with same name is introduced, it does not override, and the list comprehension acts like a sandbox for some reason, and it seems like creating a new scope in it.
>>> x = 'OLD'
>>> sample = [x for x in 'NEW']
>>> x
'OLD'
x = 5
class BlockScopeAttempt:
x = 10
print(x) # Output: 10
print(x) # Output: 5
不幸的是,当定义一个函数时,这种方法就会失效:
x = 5
class BlockScopeAttempt:
x = 10
print(x) # Output: 10
def printx2():
print(x)
printx2() # Output: 5!!!
That’s because functions defined within a class use global scope. The easiest (though not the only) way to fix this is to explicitly specify the class:
x = 5
class BlockScopeAttempt:
x = 10
print(x) # Output: 10
def printx2():
print(BlockScopeAttempt.x) # Added class name
printx2() # Output: 10
If I modify filter.py, then autoreload will detect the changes. It doesn't reload load.py, so I don't need to reload my data. This way I can prototype my filtering code in a Jupyter notebook, wrap it as a function, and then cut-paste from my notebook directly into filter.py. Figuring this out revolutionized my workflow, and converted me from a skeptic to a believer in the “Zen of Python.”