I can't import a module using the eval() function.
So, I have a function where if I do import vfs_tests as v it works. However, the same import using eval() like eval('import vfs_tests as v') throws a syntax error.
Why is this so?
Use exec:
exec 'import vfs_tests as v'
eval works only on expressions, import is a statement.
exec is a function in Python 3 : exec('import vfs_tests as v')
To import a module using a string you should use importlib module:
import importlib
mod = importlib.import_module('vfs_tests')
In Python 2.6 and earlier use __import__.
Actually. if you absolutely need to import using eval (for example, code injection), you can do it as follow in Python 3, since exec is a function:
eval("exec('import whatever_you_want')")
For example:
>>> eval('exec("from math import *")')
>>> sqrt(2)
1.4142135623730951
My little trick if you want to pass all the code as string to eval function:
>>> eval('exec("import uuid") or str(uuid.uuid4())')
'bc4b921a-98da-447d-be91-8fc1cebc2f90'
>>> eval('exec("import math") or math.sqrt(2)')
1.4142135623730951
You can use __import__ inside of eval to import something.
eval("__import__('os').system('ls')")
Related
Is from foo import * equivalent to import foo? Plese help.
The question is about python 2.7
No,
When you use import foo, to call a function from from this package you have to do : foo.my_function() whereas with from foo import * you can write my_function() directly
I think the difference is more in style of use. But I would not use from foo import *. I think it's better to be specific on what you need to import:
from foo import package_0
from foo import package_1
from foo import package_2
# etc
However, you need to add additional import every time you need a new package which can be avoided if you use import foo. But in that case you need to prefix every package inside of it with foo:
foo.package_0.some_method()
foo.package_1.another_method()
RestrictedPython module has a restricted compiler in which you can compile code and customize some python features. For example, you can replace the builtin print function.
That's what I need to do. I need to compile some code but defining my own print function. I can't use this restricted compiler because it has a lot of restrictions I don't need at now.
Do you know any other compiler in which I can define my own print function?
Just use regular Python then; in Python 2 use:
from __future__ import print_function
or use Python 3, and print() is then a function. You can redefine that function:
from __future__ import print_function
try:
# Python 2
from __builtin__ import print as builtin_print
except ImportError:
from builtins import print as builtin_print
def print(*args, **kw):
# do something extra with *args or **kw, etc.
builtin_print(*args, **kw)
Like any other built-in function you can define your own function using the same name. In the above example I used the __builtin__ / builtins module to access the original.
If you are using exec(), you can pass in the print() function you defined as an extra name in the namespace you pass in:
exec(code_to_execute, {'print': your_print_function})
For Python 2, you do need to compile the code first to switch off the print statement and enable the print() function; use the compile() function to produce a code object to pass to the exec statement:
import __future__
code_to_execute = compile(
code_to_execute_in_string, '', 'exec',
flags=__future__.print_function.compiler_flag)
I used the __future__ module to obtain the right compiler flag.
This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 9 years ago.
I have a script which imports modules on-the-fly. Because modules name are changed as soon as a new version appears, it is difficult to check if the specific module name is also changed in the script. Because of this, I keep the modules name in the top of the script, in variables, like in this example:
var1 = 'moduleName1_v04'
var2 = 'moduleName2_v08'
...................
import var1
...................
import var2
...................
But if I am writing like this, I will get an error.
The question is: how to import a module using a variable like in the example? Is it possible?
Yes, you can achieve this quite easily by using importlib.import_module:
import importlib
module = importlib.import_module(var1)
Alternatively, you can use the __import__() built-in function
>>> sys = __import__("sys")
>>> sys
<module 'sys' (built-in)>
The __import__() function is the function that the interpreter uses to import modules. However, it's discouraged to use or modify this in favor of the simpler, safer import hooks, such as the first one i mentioned above. Quoting the important docs:
This function is invoked by the import statement. It can be replaced
(by importing the builtins module and assigning to
builtins.__import__) in order to change semantics of the import
statement, but doing so is strongly discouraged as it is usually
simpler to use import hooks (see PEP 302) to attain the same goals and
does not cause issues with code which assumes the default import
implementation is in use. Direct use of __import__() is also
discouraged in favor of importlib.import_module().
Hope this helps!
Yes, you can.
For example, using importlib.import_module:
>>> var1 = 'sys'
>>> import importlib
>>> mod = importlib.import_module(var1)
>>> mod
<module 'sys' (built-in)>
Ive searched the web and this site and cant find an answer to this problem. Im sure its right in front of me somewhere but cant find it.
I need to be able to import a module based on a string. Then execute a function within that module while passing arguments.
I can import based on the string and then execute using eval() but I know this is not the best way to handle this. I also cant seem to pass arguments that way.
My current module that would be set based on a string is named TestAction.py and lives in a folder called Tasks.
This is the content of TestAction.py:
def doSomething(var):
print var
This is the code I am executing to import TestAction and execute.
module = "Tasks.TestAction"
import Tasks
mymod = __import__(module)
eval(module + ".doSomething()")
How can I make this code #1 not use eval() and #2 pass the var argument to doSomething()?
Thanks in advance!
Thanks everyone for the help. it looks like importlib combined with getattr was what I needed. For future reference here is the exact code that is working for me.
module = "FarmTasks.TestAction"
mymod = importlib.import_module(module)
ds = getattr(mymod, "doSomething")
ds("stuff")
Is the function name also variable? If not, just use your imported module:
mymod.doSomething('the var argument')
if it is, use getattr:
fun = 'doSomething'
getattr(mymod, fun)('the var argument')
According to the documentation
it is better to use importlib.import_module() to programmatically import a module.
Using this you can retrieve your module like this:
import importlib
TestAction = importlib.import_module("TestAction", package="Tasks")
After that you can simply call functions normally or by name:
TestAction.some_known_function(arg1, arg2)
getattr(TestAction, "some_other_function_name")(arg1, arg2)
I hope this answered your question, feel free to elaborate if you are still missing something.
If you use Python 2.7 or 3.1+ the easiest way to go is to use the importlib module in combination with getattr. Your code would look like that then:
import importlib
module = "Tasks.TestAction"
mymod = importlib.import_module(module)
myfunc = getattr(mymod, "doSomething")
myfunc()
I recently wrote a simple function that imports a given function, it seems to work for me:
def import_function(name):
"""Import a function by name: module.function or
module.submodule.function, etc. Return the function object."""
mod, f = name.rsplit('.', 1)
return getattr(__import__(mod, fromlist=[f]), f)
You can use it as:
f = import_function('Tasks.TestAction.doSometing')
f()
or just
import_function('Tasks.TestAction.doSometing')()
I've come across the following code in a Python script
from pprint import pprint
why not simply import pprint?
Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)
It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you?
Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name.
Your belief is correct, but it is not "aliased" in any way. It is simply named pprint, which is no violation of any Python style guide.