3

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.

3
  • What do you expect sub_mod to be? Commented Nov 11, 2013 at 23:34
  • I would like for it to be a sub module within my.set.modules Commented Nov 11, 2013 at 23:35
  • Posted my answer, please see it. Commented Nov 11, 2013 at 23:37

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.