0

Hi folks: I have been trying to execute a 'exec ()' sentence inside a Python function without success; for example when I run:

def main():
    exec( 'from MODULE import {a}'.format( a = 'funcName' ) ) 
    print( dir( funcName() ) ) 
main()

with MODULE.py as:

def funcName():
    return True

I get:

Traceback (most recent call last):
  File "0.py", line 17, in <module>
    main()
  File "0.py", line 15, in main
    print( dir( funcName() ) ) 
NameError: name 'funcName' is not defined

It seems I really missed the point here.

martineau
  • 119,623
  • 25
  • 170
  • 301
Ernesto
  • 19
  • 2
  • 1
    Welcome to SO! This is unusual code. What are you trying to achieve exactly--a dynamic function import based on a string? Thanks. – ggorlen Mar 31 '20 at 00:56
  • 1
    Don't use `exec`. – user2357112 Mar 31 '20 at 00:59
  • huh, the example code works for me – maxm Mar 31 '20 at 01:02
  • 1
    @maxm: If it does, you're on Python 2, and you should really get Python 3. – user2357112 Mar 31 '20 at 01:07
  • Right, ggorlen, you've got the point; I'm trying a dynamic function import based on a string. When I try de exec() sentence inside the main module but when trying to do it inside a function doesn't work. I really like to avoid collect all the code in the main module. Thks – Ernesto Mar 31 '20 at 01:18
  • 1
    @Ernesto: Instead of that, use [`importlib.import_module`](https://docs.python.org/3/library/importlib.html#importlib.import_module) and [`getattr`](https://docs.python.org/3/library/functions.html#getattr). – user2357112 Mar 31 '20 at 01:20
  • Thanks very much @user2357112 supports Monica. Your answer works for me. Bye – Ernesto Mar 31 '20 at 01:37

0 Answers0