function.include-once

function.include-once

[code=python] ¶
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) ¶
[/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] ¶
[code=python] ¶
import os ¶
if os.path.exists('myfile.py'): ¶
import myfile #Omitting (.py) extension. ¶
[/code] ¶

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] ¶

[b]Console - include_once:[/b] ¶
[code=python] ¶
>>> import myinclude ¶
>>> myinclude.include_once('myfile.py') ¶
here we go ¶
>>> myinclude.myfile.foo(3,4) ¶
19 ¶
>>> myinclude.myfile.a ¶
3 ¶
[/code] ¶

[b]Console - include_once - with globals():[/b] ¶
[code=python] ¶
>>> import myinclude ¶
>>> myinclude.include_once('myfile.py',globals(),'hello') ¶
here we go ¶
>>> hello.foo(3,4) ¶
19 ¶
>>> hello.a ¶
3 ¶
[/code] ¶


[b]Console - python import:[/b] ¶
[code=python] ¶
>>> import myfile ¶
here we go ¶
>>> myfile.foo(3,4) ¶
19 ¶
>>> myfile.a ¶
3 ¶
[/code]