0

Possible Duplicate:
Importing in Python

I have a couple of functions and I want to make them visible as library functions to be able to call them from other projects. I want to have them in a separate directory from common python libraries. How I should arrange my code?

Community
  • 1
  • 1
user14416
  • 2,922
  • 5
  • 40
  • 67

4 Answers4

3

You can use this in project where you want import your functions:

import sys
sys.path.append('c:\\myprojects\\MyProjDir\\')

from MyModule import MyClass 

Note, that file with name __init__.py must be placed in MyProjDir. Otherwise Python will not scan this directory. Contents of __init__.py can be left blank.

Docs:

  1. Modifying Python’s Search Path
  2. The Module Search Path
Gill Bates
  • 14,330
  • 23
  • 70
  • 138
  • 1
    Avoid manipulations of sys.path in your code. This makes it fragile, and not reusable on other systems. – Keith Dec 30 '12 at 23:49
  • I would appreciate if you explain more solid methods. (`virtualenv`?) – Gill Bates Dec 31 '12 at 01:32
  • 1
    Use setuptools (based on distutils). It will manage `.pth` files for you, by using commands such as `develop` to set up develop mode. You can then also deploy distributions from the same code base. – Keith Dec 31 '12 at 03:30
1

First of all you have to make a package containing your code. A quick introduction can be found here: http://guide.python-distribute.org/introduction.html There are different options how to manage your package in relation to other projects. I would propose to use setuptools to create a distributable package. If you want to isolate your development from the default python installation, have a look at http://pypi.python.org/pypi/virtualenv.

Achim
  • 15,415
  • 15
  • 80
  • 144
0

You must save this function in some my file, and from other file or module use import.

Mihai8
  • 3,113
  • 1
  • 21
  • 31
0

Define these functions in a seperate file and use import to refer them. A helpful link (modules in python): http://docs.python.org/3/tutorial/modules.html

Huang Zhu
  • 21
  • 2