How about this:

def test():
    exec (code, globals())
    f()
Answer from Yevgen Yampolskiy on Stack Overflow
🌐
Finxter
blog.finxter.com › home › learn python blog › how to import libraries in python’s exec() function?
How to Import Libraries in Python's exec() Function? - Be on the Right Side of Change
February 4, 2021 - We can restrict exec() from accessing our global import statements by placing an empty dictionary {} in the globals parameter. This will stop the external libraries from being imported outside or our ‘program’ code string. In the example below we are going to import two of the Python Standard Library modules to better illustrate our point:
Discussions

Import vs exec functions for using modules
If you haven't it yet, I highly recommend you read through the official docs on imports and packages: https://docs.python.org/3.6/tutorial/modules.html#packages Imo, I think you are overthinking this import os os.getcwd() from os import getcwd getcwd() The two methods are nearly identical, the only difference being the way you access the imported objects. If you are curious about performances, you can read a note about it here: https://stackoverflow.com/q/3591962/4411196 As for reloading, I'm not sure why you would need this, as its rarely needed, and often not a good idea: https://stackoverflow.com/q/5516783/4411196 As for exec, I'm a little confused by what you are referring to. The builtin in exec function doest one thing - it takes a string and executes it (ie. exec("2+2") will output 4) https://pythonprogramming.net/python-exec-tutorial/ More on reddit.com
🌐 r/learnpython
6
1
December 11, 2017
django - Python: 'import *' vs execfile - Stack Overflow
Using execfile function will result in the evaluation of the Python source file (.py) every time the settings file is evaluated. You are executing the Python parser each time. Using import wouldn't necessarily do this (might use the .pyc file). Generally the first time you run a project in ... More on stackoverflow.com
🌐 stackoverflow.com
How to make modules from exec("import xxx") in a Python function available? - Stack Overflow
I have written myself a simple function that sieves through my Python folder and look for where a possible module is. What I want to do is simple. I pass a string of module import and the function ... More on stackoverflow.com
🌐 stackoverflow.com
October 19, 2015
exec statement python and importing module - Stack Overflow
Im trying to import a module using exec statement but it fails, code.py def test(jobname): print jobname exec ('import ' + jobname) if __name__ = '__main__': test('c:/python27/test1.py') More on stackoverflow.com
🌐 stackoverflow.com
October 22, 2012
🌐
Programiz
programiz.com › python-programming › methods › built-in › exec
Python exec() (With Examples)
It's a good idea to check the methods and variables you can use with the exec() method. You can do this with the help of the dir() method. # import all the methods from math library from math import *
🌐
Reddit
reddit.com › r/learnpython › import vs exec functions for using modules
r/learnpython on Reddit: Import vs exec functions for using modules
December 11, 2017 -

Hi guys, I am currently reading learning python by O'Reilly and they were discussing different ways of importing modules. I am new so please correct my terminology. I was wondering what the difference is between import module, from module import x and exec.

Import Module allows me to import the module but requires the function reload if my_module were to be edited. This also has its own namespace. E.g module.function

From module import function, is like import but it overrides variables.

Exec in python 3 uses the current version of the module if any changes were made.

So is this the reasons why we would want to use each one.

Import module - pros own namespace. Cons import all function, has to reload

From module import function - pros can choose function, cons overrides variables, has to reload

Exec - pros uses latest changes to file(does not need reload) cons overrides variables

Sorry if format is bad, Doing this on my phone , will edit later

Would this be an appropriate stack overflow question?

edit:Got this from stack overflow, now trying to figure out when exec is used instead

After import x, you can refer to things in x like x.something. After from x import *, you can refer to things in x directly just as something. Because the second form imports the names directly into the local namespace, it creates the potential for conflicts if you import things from many modules. Therefore, the from x import * is discouraged.

🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.14.4 documentation
If and when a module spec is found, the import machinery will use it (and the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import: module = None if spec.loader is not None and hasattr(spec.loader, 'create_module'): # It is assumed 'exec_module' will also be defined on the loader.
🌐
Armin Ronacher
lucumr.pocoo.org › 2011 › 2 › 1 › exec-in-python
Be careful with exec and eval in Python | Armin Ronacher's Thoughts and Writings
February 1, 2011 - However there are also people that use exec to load actual Python code that declares functions and classes. This is a very popular pattern in some plugin systems and the web2py framework. Why is that not a good idea? Because it breaks some (partially unwritten) conventions about Python code: Classes and functions belong into a module. That basic rule holds for all functions and classes imported from regular modules:
Top answer
1 of 3
14

Using execfile function will result in the evaluation of the Python source file (.py) every time the settings file is evaluated. You are executing the Python parser each time. Using import wouldn't necessarily do this (might use the .pyc file). Generally the first time you run a project in Python (at least, cPython) it gets compiled to bytecode and not recompiled again. You are breaking that. This isn't necessarily a problem, but you should be aware of it.

Using execfile will also result in all of the imports you may have in the settings_local.py file being re-evaluated in the module scope of the settings.py file. Using import * would have included all items in the settings_local.py module scope. The net effect is the same (all items included in settings_local.py module scope are included in settings.py) but the method is different.

Finally, it's normal for modules to be executed as modules rather than included. It is reasonable for code to include things such as os.path.dirname(__file__). If any code did use this, you would confuse it as the code would no longer be executing in the module that the author might reasonably have expected.

In my experience, people use import not execfile. Django is very much 'convention over configuration'. Follow the convention.

2 of 3
9

Another difference: execfile gets a context dictionary; the global context by default or a specified dictionary. This could allow some strange things

dont_do_this.py:

# Probably not a good thing to do
z=x+1  # an expression that involves an un-defined field

Obviously,

from dont_do_this import *

fails.

However,

d={'x':1}
execfile( 'dont_do_this.py', d )

is OK and results in d=={'x':1, 'z':2}

Note that

x=1
execfile( 'dont_do_this.py' )

is OK and results in the variable z being added to the globals.

Find elsewhere
Top answer
1 of 2
6

exec executes code in the current scope. Inside a function, this means the (function-) local scope.

You can tell exec to put variables in another scope by giving it a tuple (code, scope). For example, you can use globals() to make names available at the module level.

Be aware, that globals

is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

Thus, in your example, you have to pass the desired scope to your utility function:

anyimport.py:

class anyimport(object):
    def __init__(self, importmodule, scope):
        exec (importmodule, scope)

test.py:

a = 42
b = 'foo'

main.py:

from anyimport import anyimport

if __name__ == '__main__':
    anyimport('from test import *', globals())
    # 42 foo
    print a, b

Test it with python main.py. Make sure all files are present in the current directory.

Alternative Solution

If you are not bound to use exec, a more elegant way would be to use the import utilities provided by Python.

The following, taken from https://stackoverflow.com/a/4526709/453074 , is equivalent to from some.package import *:

[...] it's more convenient to user importlib:

globals().update(importlib.import_module('some.package').__dict__) 

.

2 of 2
2

You might want to try something like this:

_globals = {}
code = """import math;"""
code += """import numpy;"""
code = compile(code, '<string>', 'exec')
exec code in _globals

It's safer than just doing an exec, and it should import correctly inside a function's local scope.

You can then update globals() with whatever modules (or functions) you import.

When using exec for functions, you can get a handle to globals with g = globals(), then do an update on g. For modules, you should do another step... you will want to also update the modules in sys.modules as well.

UPDATE: to be explicit:

>>> def foo(import_string):
...   _globals = {}
...   code = compile(import_string, '<string>', 'exec')
...   exec code in _globals
...   import sys
...   g = globals()
...   g.update(_globals)
...   sys.modules.update(_globals)
... 
>>> foo('import numpy as np')
>>> np.linspace
<function linspace at 0x1009fc848>
🌐
DataFlair
data-flair.training › blogs › python-exec-function
Python exec Function - Example and Risk - DataFlair
November 24, 2018 - When you give your users the liberty to execute any piece of code with the Python exec() function, you give them a way to bend the rules. What if you have access to the os module in your session, and they borrow a command from that to run? Say you have imported os in your code.
🌐
Stack Overflow
stackoverflow.com › questions › 47247787 › importing-module-in-exec-statement-in-python
import - Importing module in exec-statement in python - Stack Overflow
November 12, 2017 - class foo: modules = { 'string' : 0 } def prepare(self): for modName in self.modules.keys(): print(locals()) exec("import {} as tmp".format(modName)) print(locals()) self.modl = tmp somevar = foo() somevar.prepare() print(somevar.modl.digits) ... {'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>} {'tmp': <module 'string' from '/usr/lib/python2.7/string.pyc'>, 'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>} 0123456789
🌐
Real Python
realpython.com › python-exec
Python's exec(): Execute Dynamically Generated Code – Real Python
November 10, 2022 - To illustrate this problem, get back to the Python interpreter example that uses exec() for code execution: ... Now say that you want to use this technique to implement an interactive Python interpreter on one of your Linux web servers. If you allow your users to pass arbitrary code into your program directly, then a malicious user might provide something like "import os; os.system('rm -rf *')".
🌐
Codecademy
codecademy.com › docs › python › built-in functions › exec()
Python | Built-in Functions | exec() | Codecademy
August 24, 2023 - This example uses exec() to execute Python code from a file code.txt, which contains Python commands: #code.txt · import datetime · current_time = datetime.datetime.now() print(current_time) Copy to clipboard · Copy to clipboard · The content of the file code.txt is read until the end of the file (EOF) into a string.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › exec › python-exec
Python exec() function | What is Python exec()? | Why do we use exec()? |
August 18, 2021 - # Python program to illustrate exec() by accepting user input code code = input('Enter a Python code: ') exec(code) ... Let us assume we have imported an ‘os’ module while working on a Unix system such as MacOS, Linux, etc. Now, this ‘os’ module provides a flexible way to exploit operating system features such as reading and writing to files.
🌐
AskPython
askpython.com › home › understanding the python exec() method
Understanding the Python exec() Method - AskPython
August 6, 2022 - In the previous example, we simply executed some set of instructions in Python passing the object argument to the exec() method. But, we didn’t see the names in the current scope. Now let us use the dir() method to get the list of current methods and names with math module included before calling the exec() method. from math import * exec("print(pow(2, 5))") exec("print(dir())")
🌐
DEV Community
dev.to › sachingeek › how-to-use-exec-in-python-everything-you-need-to-know-380f
How to Use exec() in Python - Everything You Need to Know - DEV Community
July 30, 2023 - Inside the exec() function, only the slice() method and all built-in methods can be executed. Even though the slice() method is not from the datetime module, it works perfectly here. We can also limit the use of __builtins__ by setting it to None. from datetime import * # Setting globals parameter to none globals_param = {'__builtins__': None} # Setting locals parameter to take only print(), slice(), sum() and dir() locals_param = {'print': print, 'dir': dir, 'slice': slice, 'sum': sum} # Allowed methods directory exec('print(dir())', globals_param, locals_param) exec('print(f"Sum of numbers: {sum([4, 6, 7])}")', globals_param, locals_param)
🌐
docs.python.org
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.4 documentation
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...