about python modules

bockman at virgilio.it bockman at virgilio.it
Wed May 21 08:48:25 EDT 2008


On 21 Mag, 14:31, srinivas <srinivas.puvv... at gmail.com> wrote:
> hi friends i am new to python programming.
> i am using Python 2.5 and IDLE as editor.
> i have developed some functions in python those will be calling
> frequently in my main method .
> now i want to know how to import my functions folder to python in
> sucha way that the functions in functions folder should work like
> python library modules .
>
> i have  python in folder C:\python25\..
> and functions folder D:\programs\Functions\
>
> pls help me friends how to do that.

You have two choices:

1. In this way you can import single modules (files) in tour folder

import sys
sys.path.append(r'D:\programs\Functions\')
import my_module_1
import my_module_2

and then  use whatever you have in the modules:

my_module_1.my_function()
print my_module_1.my_variable


2.
If you add an empty python module called __init__.py inside the folder
D:\programs\Functions\,
then python will handle the folder as a package (i.e. a group of
modules) and  you can import
them in this way:

sys.path.append(r'D:\programs\')
import Functions # I'm not sure this is needed ...
from Functions import my_module_1, my_module_2

And then use whatever is in your modules as in case 1.

If you put any code in __init__.py, this code will be executed when
the import Functions
statement is executed. This can be handy in some cases, e.g. if you
have subfolders of
Function folder and want to extend sys.path to include all them.

For more details, read the section 6 of Python tutorial.

HTH

Ciao
------
FB



More information about the Python-list mailing list