Aug-09-2023, 07:45 AM
(This post was last modified: Aug-09-2023, 07:45 AM by Gribouillis.)
(Aug-09-2023, 04:11 AM)SpongeB0B Wrote: I've dig the WWW but I found only very old results that lead to create some Dictionary...Variables in Python are kept in namespaces, which have a dictionary-like semantics. For example global variables in a module are kept in the
globals()
dictionary, which you could also access as vars(sys.modules[__name__])
. You can update these dictionaries to create module-level variables.Usually however, this is bad practice and it is better to use another dictionary that your program creates.
I see a good use case for this, which is lazy imports of subpackages in a package Spam:
# Spam.__init__.py def __getattr__(name): from importlib import import_module submodule = import_module(name, __package__) globals()[name] = submodule return submoduleNow in client code
import Spam # accessing Spam.eggs automatically imports submodule Spam.eggs Spam.eggs.somefunction() # on second access, nothing is imported because eggs is now a member of Spam Spam.eggs.otherfunction()Even in this example, one could avoid updating
globals()
directly by using setattr(import_module(__name__), name, submodule)
, emphasizing that we are "setting an attribute" instead of "creating a variable".A different example of creating a variable 'eggs' in the Python shell
>>> import sys >>> module = sys.modules[__name__] >>> module.eggs = 'Humpty Dumpty' >>> eggs 'Humpty Dumpty'