Thursday, March 24, 2011

Getting attributes of a Python package that I don't have the name of, until runtime

In a Python package, I have a string containing (presumably) the name of a subpackage. From that subpackage, I want to retrieve a tuple of constants...I'm really not even sure how to proceed in doing this, though.

#!/usr/bin/python
"" The Alpha Package
Implements functionality of a base package under the 'alpha' namespace
""

def get_params(packagename):
    # Here, I want to get alpha.<packagename>.REQUIRED_PARAMS
    pass

So, later in my code I might have:

#!/usr/bin/python
import alpha

alpha.get_params('bravo') # should return alpha.bravo.REQUIRED_PARAMS
alpha.get_params('charlie') # should return alpha.charlie.REQUIRED_PARAMS
From stackoverflow
  • If I correctly understand what you want, I think something roughly like this should work:

    def get_params(packagename):
        module = __import__('alpha.%s' % packagename)
        return module.__dict__['REQUIRED_PARAMS']
    

0 comments:

Post a Comment