PYTHON require_once

is this article helpful?
|
Python replacement for PHP's require_once [ edit | history ]
def require_once(filename, glob = globals(), modulename = ''):
	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 myfile #Omitting (.py) extension.


Successive call don't have any effect as in require_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:
Python 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 - require_once:
>>> import myrequire
>>> myrequire.require_once('myfile.py')
here we go
>>> myrequire.myfile.foo(3,4)
19
>>> myrequire.myfile.a
3


Console - require_once - with globals():
>>> import myrequire
>>> myrequire.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



or as lib you can try :
from file import *

PHP require_once

PHP original manual for require_once [ show | php.net ]

require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once() documentation for information about the _once behaviour, and how it differs from its non _once siblings.