Basj
Basj

Reputation: 46493

Using a folder for personal modules in Python

I have created a folder named C:\Python27\Lib\site-packages\perso and inside I have put a file mymodule.py. The goal is to have this module accessible from any future Python script.

Let's do a D:\My Documents\test.py file:

import mymodule   #fails
import perso.mymodule   #fails

Why does it fail? How to import a module from C:\Python27\Lib\site-packages\perso? What are the best practice for using user-modules in all Python scripts of the same computer?

Upvotes: 2

Views: 2128

Answers (2)

Gal Dreiman
Gal Dreiman

Reputation: 4009

Python Modules:

In order to create a module you can do the following:

  1. under <Python_DIR>\Lib\site-packages:
    put you directory <module>. This directory contains your classes.
  2. In <Python_DIR>\Lib\site-packages\<module> put an init file __init__.py,
    This file define what's in the directory, and may apply some logic if needed.
    for example: __all__ = ["class_1", "class_2",].

Than, to import:

from <your_module> import <your_class>

For more information, read this.

Upvotes: 2

nick_gabpe
nick_gabpe

Reputation: 5775

  1. check PythonPath
  2. create __init__.py to use perso as package

Upvotes: 3

Related Questions