问题
I am trying to build some dynamic code that parses a text file with objects named from the imports at the top of the module... right now I iterate through all items in sys._getframe(0) to find f_globals. Is there a more pythonic way of finding f_globals?
import re
import sys
import inspect
## Import all Object models below
from Models.Network.Address import MacAddress as _MacAddress
from Models.Network.Address import Ipv4Address as _Ipv4Address
class Objects(object):
"Define a structure for device configuration objects"
def __init__(self):
"Initialize the Objects class, load appropriate objects"
self.objects = dict()
for name, members in inspect.getmembers(sys._getframe(0)):
if name == 'f_globals':
for modname, ref in members.items():
if re.search('^_[A-Za-z]', modname):
self.objects[modname] = ref
return
回答1:
Did you want globals()?
回答2:
Can't You just use
globals()
?
Moreover, is there a reason why not explicitly specify object to iterate over? That way, you are not prone to "globals" "pollution" by some correlated imports.
来源:https://stackoverflow.com/questions/5782651/pythonic-way-to-find-the-name-of-global-namespace-imports