PHP » PYTHON |
login |
register |
about
|
function.include-oncefunction.include-onceimport 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) ¶ [/code] ¶ ¶ ¶ If you know module name (not in run-time) you can also [i]include once[/i] myfile.py in python with import: ¶ [code=python] ¶ import myfile ¶ [/code] ¶ Omitting (.py) extension. This is not exactly the same as include_once but more similar to require_once. ¶ ¶ Successive call don't have any effect as in [i]include_once[/i] php directive as described in [url=http://docs.python.org/tutorial/modules.html]python documentation[/url]: ¶ ¶ [quote] ¶ 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). ¶ [/quote] ¶ ¶ ¶ [b]Interactive mode - note:[/b] ¶ 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: ¶ ¶ [b]myfile.py[/b] ¶ [code=python] ¶ def foo(x,y): ¶ return x+y*4 ¶ ¶ a = 3 ¶ print 'here we go' ¶ [/code] ¶ ¶ Console: ¶ [code=python] ¶ >>> import myfile ¶ here we go ¶ >>> myfile.foo(3,4) ¶ 19 ¶ >>> myfile.a ¶ 3 ¶ [/code] |