Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't an import in an exec in a function work?

I can put an import statement in a string, exec it, and it works (prints a random digit):

code = """ import random def f():     print random.randint(0,9) """  def f():     pass  exec code f() 

Now, if I put exec code and f() in their own function and call it, it doesn't work.

def test():     exec code     f()  test() 

It says NameError: global name 'random' is not defined.

like image 807
Alex Varga Avatar asked Sep 20 '12 01:09

Alex Varga


People also ask

What is exec () used for?

The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).

Can you import inside a function?

Most of the time if you can do something in a function, you can do it in global scope or in a class definition or vice versa. There's an exception for from ... import * , which works at global scope but not inside a function.

Why is the use of import all statement not recommended?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.

Can you import a module in a function?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.


1 Answers

How about this:

def test():     exec (code, globals())     f() 
like image 114
Yevgen Yampolskiy Avatar answered Sep 20 '22 19:09

Yevgen Yampolskiy