I have a case where the "names" of classes of interest are available.
Is it possible, without creating an instance of the class, to check for the existing and value of Class attributes ?
E.g., I know that one can do this
class Universal:
answer = 42
all_knowing_one_class = Universal
solution = 'answer'
unknown = 'a great mystery'
print('The universal answer is', getattr(all_knowing_one_class, solution, unknown) )
But not clear how to do this if one starts with the string name of the class
class Universal:
answer = 42
all_knowing_one_class_name = 'Universal'
solution = 'answer'
unknown = 'a great mystery'
print('The universal answer is', ??? )
I know that I could create a local mapping between name and class, but wondered if there was a more pythonic way that I could learn :-)
CodePudding user response:
You don't need to create a local mapping between name and class, because such a mapping already exists - locals()
. The dynamic namespace lookup can be done with either getitem or getattr style access: it's getattr if you have the module instance itself, and getitem if you have the namespace (i.e. the module's __dict__
).
If you're working within the same namespace:
the_class = locals()[all_knowing_one_class_name]
# or...
import __main__
the_class = getattr(__main__, all_knowing_one_class_name)
If the Universal
class is defined in a different namespace, other_module.py
say:
import other_module
the_class = vars(other_module)[all_knowing_one_class_name]
# or
the_class = getattr(other_module, all_knowing_one_class_name)
If the name of "other_module.py" is also dynamic:
import importlib
other_module = importlib.import_module("other_module")