Created
November 11, 2020 14:11
-
-
Save devilholk/cd8999123412891eb013ce127cb3aa55 to your computer and use it in GitHub Desktop.
A workaround for a nested scope not being able to access its parent scope
This file contains 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
#Note that this is not recommended, we may not be able to rely on locals() being mutable on other platforms or future versions | |
#Also note https://stackoverflow.com/questions/29333359/python-class-scoping-rules | |
scope_transfer = dict() | |
class my_namespace: | |
class some_thing: | |
pass | |
scope_transfer.update(locals()) | |
class thing_that_refers_to_some_thing: | |
locals().update(scope_transfer) | |
item = some_thing | |
del scope_transfer | |
print(my_namespace.thing_that_refers_to_some_thing.item) | |
#Output: <class 'scope_example.my_namespace.some_thing'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, we are taking everything in locals() including
__name__
it is better with explicit import of the references we care about.