PHP » PYTHON |
login |
register |
about
|
PYTHON include_once
is this article helpful?
|
Python replacement for PHP's include_once
[
edit
| history
]
import os def include_once(filename, glob = globals(), modulename = ''): if os.path.exists(filename): filename = filename[:-3] if filename.endswith('.py') else filename; module = modulename if (modulename != '') else filename glob[module] = __import__(filename, globals(), locals(), [], -1) If you know module name (not in run-time) you can also include once myfile.py in python with import: import os if os.path.exists('myfile.py'): import myfile #Omitting (.py) extension. Successive call don't have any effect as in include_once php directive as described in python documentation: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use reload(), e.g. reload(modulename). Interactive mode - note: Import does not enter the names of the object, functions, classes, etc ... defined in myfile.py directly in the current symbol table. You can anyway access them using module name: myfile.py def foo(x,y): return x+y*4 a = 3 print 'here we go' Console - include_once: >>> import myinclude >>> myinclude.include_once('myfile.py') here we go >>> myinclude.myfile.foo(3,4) 19 >>> myinclude.myfile.a 3 Console - include_once - with globals(): >>> import myinclude >>> myinclude.include_once('myfile.py',globals(),'hello') here we go >>> hello.foo(3,4) 19 >>> hello.a 3 Console - python import: >>> import myfile here we go >>> myfile.foo(3,4) 19 >>> myfile.a 3 include_once()The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once. include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc. See the include() documentation for information about how this function works.
|
more
Recently updated
more
Most requested
more
Last requests
|