Mike Pennington
Mike Pennington

Reputation: 43077

Pythonic way to find the name of global namespace imports

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

Upvotes: 0

Views: 615

Answers (2)

Almad
Almad

Reputation: 5893

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.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Did you want globals()?

Upvotes: 2

Related Questions