Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign variable to module name in python function

Tags:

python

module

I have a set of modules, and I want to be able to call one of them within a function based on an argument given to that function. I tried this, but it doesn't work:

from my.set import modules

def get_modules(sub_mod):
    variable = sub_mod
    mod_object = modules.variable
    function(mod_object)

I get:

AttributeError: 'module' object has no attribute 'variable'

It's not taking the argument I give it, which would be the name of a module that exists under my.set.modules. so if I called the function get_modules(name_of_mod_under_modules), I would like the line modules.variable to be "modules.name_of_mod_under_modules" which I could then have as an object passed to mod_object.

like image 432
numb3rs1x Avatar asked May 17 '26 21:05

numb3rs1x


1 Answers

In your current code, you're looking for modules.variable which doesn't exist, hence the error! That's not how you get an attribute of an object.

To achieve what you wanted, use the getattr function.

mod_object = getattr(modules, variable)
like image 144
aIKid Avatar answered May 20 '26 10:05

aIKid