I am learning Python and am still a beginner, although I have been studying it for about a year now. I am trying to write a module of functions which is called within a main
The simple approach of exec
(python 3) or execfile
(python 2) as mentioned in the comments by @abarnert may be useful for some workflows. All that is needed is to replace the import line with:
exec( open("module1.py").read() ) # python 3
and then you can simply call the function with cool()
rather than module1.cool()
. Within cool()
, the variable pi
will behave like a global, as the OP had originally expected.
In a nutshell, this is simply hiding a function definition that would otherwise appear at the top of your main program and has both advantages and disadvantages. For large projects with multiple modules and imports, using exec
(instead of a proper namespaces) is probably a mistake as you don't generally want to keep too many things within a single global namespace.
But for simple cases (like using Python as a shell script) exec
gives you a simple and concise way to hide shared functions while letting them share the global namespace. Just note that in this case you might want to give extra thought to how you name your functions (e.g. use v1_cool
and v2_cool
to keep track of different versions since you can't do v1.cool
and v2.cool
).
One less obvious disadvantage of using exec
here is that errors in the executed code may not display the line number of the error although you can work around this: how to get the line number of an error from exec or execfile in Python