2

Short version:

Say I have a string str and a file functions.py from which I would like to import a method whose name is stored in str.

How do I go about it? I would like something like:

from functions.py import str

but have str evaluated and not to import the method 'str' (which doesn't exist).

After some googling I came as close (I hope) as:

func_name = str
_tmp = __import__('functions.py', globals(), locals(), ['func_name'], -1)
func = ???? <what to put here?>

Thanks in advance.

EDIT: TMI.

1
  • Note you should import functions and not functions.py. Commented Oct 16, 2011 at 19:54

3 Answers 3

5

Assuming your code to import the module into _tmp works then the final step is simply:

func = getattr(_tmp, func_name)
Sign up to request clarification or add additional context in comments.

Comments

1

The getattr method gives you an attribute of a given object. Since global functions are attributes of the module they are in, you can use this:

import functions

funcName = 'doSomething'
f = getattr(functions, funcName)
f(123)

There is no need to use __import__, as that's usually needed only when you don't know the module name in advance.

Comments

0

If your goal is to save memory by only importing the functions you need, don't bother; even if you used the from ... import ... construct, Python still imports the whole module, just that it only adds to the current dictionary those members that you explicitly requested (the others are still in memory, just that they're not accessible directly).

With that in mind, I would do something along these lines:

import functions
the_name = self.name.lower() + str(i)
the_func = getattr(functions, the_name)

2 Comments

TypeError: 'module' object is not subscriptable
@Mark Ah, right. You forget the little bits after not using the language for some time. :)

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.