2

Ok so I have two files, filename1.py and filename2.py and they both have a function with same name funB. The third file process.py has function that calls function from either files. I seem to be struggling in calling the correct function.

In process.py:

from directoryA.filename1 import funB
from directoryA.filename2 import funB

def funA:

    #do stuff to determine which filename and save it in variable named 'd'
    d = 'filename2'
    # here i want to call funB with *args based on what 'd' is 

So i have tried eval() like so:

 call_right_funB = eval(d.funB(*args))    

but it seems not to work.

Any help is appreciated.

4
  • Can't you just from directoryA.filename1 import funB as f1 in this case? Or do you really need to dynamically lookup the module? Commented Sep 16, 2017 at 9:21
  • @JonClements Thanks, Yes I need to dynamically look up the module Commented Sep 16, 2017 at 9:27
  • They're not "directory.filename" but "package.module" or am I missing something? Commented Sep 16, 2017 at 9:45
  • @AnttiHaapala its 'package.module' I used 'directory.filename' for simplifying and clarification purpose only Commented Sep 16, 2017 at 9:49

1 Answer 1

3

The problem is, you can't use eval() with a combination of a string and a method like that. What you have written is:

call_right_funB = eval('filename'.funB(*args))

What you can do is:

call_right_funB = eval(d + '.funB(*args)')

But this is not very pythonic approach. I would recommend creating a dictionary switch. Even though you have to import entire module:

import directoryA.filename1
import directoryA.filename2

dic_switch = {1: directoryA.filename1, 2: directoryA.filename2}
switch_variable = 1
call_right_funB = dic_switch[switch_variable].funB(*args)

Hope it helps.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you, the first "unpythonic" way works fine. With Dictionary switch how would i call then function 'funB'
You are welcome :-) call_right_funB = dict_switch[switch_variable].funB(*args) should work fine. Edit: If you are using it only once, you can also do: call_right_funB = {1: filename1, 2: filename2}[switch_variable].funB(*args)
I get AttributeError: 'str' object has no attribute 'funB'
@darth haven't you write dictionary values as strings? Notice that in dict_switch they are saved as keywords, not as strings.
It was string but if i save as keywords I get TypeError: 'module' object is not subscriptable
|

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.