Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import functions from other projects in Python?

Tags:

python

import

I have some code in a project which I'd like to reuse in another project. What do I need to do (in both folders) so that I can do this?

The directory structure is something like:

  • Foo
    • Project1
      • file1.py
      • file2.py
  • Bar
    • Project2
      • fileX.py
      • fileY.py

I want to use functions from file1.py and file2.py in fileX.py and fileY.py.

like image 548
Big Dogg Avatar asked Jan 24 '13 19:01

Big Dogg


2 Answers

Ideally both projects will be an installable python package, replete with __init__.py and setup.py. They could then be installed with python setup.py install or similar.

If that is not possible, don't use execfile()! Manipulate the PYTHONPATH to add Foo so that import Project1.file1 works.

For example, from Project2/fileX.py:

from os import path import sys sys.path.append(path.abspath('../Foo'))  from Project1.file1 import something 

However, the real answer is to make each a discrete installable package.

like image 178
Rob Cowie Avatar answered Sep 22 '22 07:09

Rob Cowie


There's a lot going on here. you should read about python packages and module management http://docs.python.org/2/tutorial/modules.html#packages but the basic idea is that fileX needs to know where file1 and file2 are in order to use them.

To turn a folder into a package, it just needs to contain an __init__.py file. What I would suggest you do is (in a terminal)

$ touch Foo/__init__.py $ touch Foo/Project1/__init__.py 

(assuming you're using unix/linux).

Then somehow, fileX needs to know where the Foo package is. You can call sys.path.append(PATH) where PATH is the location of Foo.

finally inside fileX.py you'd have

import sys sys.path.append(PATH) #replace PATH with the path to Foo  from Foo.Project1 import file1  #use its functions file1.function_name(argument) 

if you really want to just say function_name without the preceeding file1. you can import all of its functions by saying from Foo.Project1.file1 import * however please note that from module import * is highly frowned upon as it mixes names and make code less readable and understandable

like image 36
Ryan Haining Avatar answered Sep 18 '22 07:09

Ryan Haining