Question

Something along the lines of:

In one file:

FOO_CONST = 'bar'

def some_function(baz)
    return do_something_with(baz)

from somewhere import something

blah = something()

In another file:

my_stuff = import_as_dict("module")

And my_stuff would essentially be the equivalent of:

{
    'FOO_CONST': 'bar',
    'some_function': <function my_function at ...>,
    'blah': 'I am the result of calling the function "somewhere.something".',
}

Any libraries that could do that out of the box?

UPDATE:

Since vars(module) == module.__dict__ I have upvoted two answers but have accepted the one with a bit more data. This is the code which returns pretty much exactly what I had in mind:

my_stuff = {(key, var) for key, var in vars(module).items() if not key.startswith('__')}
Was it helpful?

Solution 2

import module
my_stuff = module.__dict__

Note that this dict is the actual dict the module uses to hold its attributes. If you do my_stuff['foo'] = 3, module has a new foo attribute equal to 3.

If you just want to get attributes by names determined at runtime, you don't really need the dict. You could do

thing = getattr(module, thingname)

OTHER TIPS

How about using vars?

import module
my_stuff = vars(module)

If you only care about the way you access module members, you can use:

my_sys = import_as_dict("sys")
print my_os["sys"]

With the following code:

import imp


class DictProxy(object):
    def __init__(self, target):
        super(DictProxy, self).__init__()

        self.target = target

    def __getitem__(self, key):
        return getattr(self.target, key)

    def __setitem__(self, key, value):
        setattr(self.target, key, value)


def import_as_dict(module_name):
    file_, pathname, description = imp.find_module(module_name)
    module = imp.load_module(module_name, file_, pathname, description)
    dict_module = DictProxy(module)
    return dict_module

Using imp for the imports will keep your global context clean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top