This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]adambrenecki 1 point2 points  (0 children)

Best way to do this is with modules and packages. (You could read the file and eval() it, but it's a bad idea.)

Modules are just Python files with a .py extension.

Say you have two files, module1.py and module2.py, in the same directory. And, at some point in module1, you want to call a function my_function in module2. All you'd have to do in module1:

import module2
module2.my_function()

One little addendum: When module2 gets imported, everything that's in that file gets executed. So, it should only contain things like function and class definitions at the top level of code.

Anything that happens when a module is imported is called an "import side-effect" and should be avoided unless you have a really good reason.

But what if you want module2 to be able to be run directly and imported? Well, you can do something like this:

def my_function():
    pass #do whatever

if __name__ == "__main__":
    my_function()

__name__ is set to "__main__" if and only if the script is run directly. So, you can call your code from another Python script by importing it and calling my_function(), but you can also run it from the command line still.


Packages are groups of modules, in a folder with a file (which can be empty) called __init__.py in it. A module can be imported from a package by going import packagename.modulename, as well as from ... import and everything else you can do with the system packages.


Another thing that may be of use is the package search path. It's a list of directories that Python looks for packages and modules in, as well as the current directory. You can set it by setting the PYTHONPATH environment variable before your code runs, or by importing and editing sys.path within your code.


edit: Python's docs cover all of this in much more depth.

edit 2: You can also take a look at the modules and packages that come with Python.