I have a Python 2.x module.py file that looks like this:
class A(object):
KEYWORD = 'Class A'
class B(A):
KEYWORD = 'Class B'
class C(object):
pass
def list_class_keywords():
for name in globals():
print name, hasattr(name, 'KEYWORD')
if __name__ == '__main__':
list_class_keywords()
In list_class_keywords(), I’m looping through all of the objects of this file module and testing if the object has an attribute KEYWORD. Clearly it isn’t working, since name is a string. How should I rewrite list_classes to get what I’m looking for?
Update: thanks to Ignacio for the hint. Here is the updated code:
def list_class_keywords():
global_dict = globals()
for name in global_dict:
obj = global_dict[name]
print name, hasattr(obj, 'KEYWORD')
1 Answer