Skip to content

Instantly share code, notes, and snippets.

@devilholk
Created November 11, 2020 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devilholk/cd8999123412891eb013ce127cb3aa55 to your computer and use it in GitHub Desktop.
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
#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'>
@devilholk
Copy link
Author

devilholk commented Nov 11, 2020

Note, we are taking everything in locals() including __name__ it is better with explicit import of the references we care about.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment