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

StackOverflow https://stackoverflow.com/questions/474331

  •  19-08-2019
  •  | 
  •  

Question

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
Was it helpful?

Solution

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']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top