Background:
I have a pure-Python module that defines a few sentinels:
foo = object()
# for backwards compatibility
bar = foo
I'd like to get a mapping between the object instances and the variable names. To do that, I import the module and loop over the variables:
signals = {}
for name, obj in vars(module).items():
if type(obj) == object:
signals[obj] = name
Problem:
The order of the variables isn't preserved, so bar ends up wrongly replacing foo in the mapping.
How do I get only the variables defined like foo = object() and not bar = foo?
Somewhat working solutions:
I know it can be done with the ast module, but my module may not have a corresponding .py file, so inspect.getsource(module) just returns the contents of the pyc file. ast.parse() won't parse that and I don't really want to add a new dependency.
It can also be done with the symtable module via the Symbol.is_referenced() method, but that suffers from the same problem as the ast approach.
Is there an elegant way of doing this without hard-coding the mapping?