gat
gat

Reputation: 2990

Import a module in Python

I have an improperly packaged Python module. It only has __init__.py file in the directory. This file defines the class that I wish to use. What would be the best way to use it as a module in my script?

** EDIT **

There was a period (.) in the the name of the folder. So the methods suggested here were not working. It works fine if I rename the folder to have a valid name.

Upvotes: 4

Views: 126

Answers (3)

aruisdante
aruisdante

Reputation: 9075

It's not necessarily improperly packaged. You should be able to do from package import X just like you would normally. __init__.py files are modules just like any other .py file, they just have some special semantics as to how they are evaluated in addition to the normal usage, and are basically aliased to the package name.

Upvotes: 0

yegle
yegle

Reputation: 5865

Put __init__.py into directory my_module, make sure my_module is in sys.path, and then from my_module import WHAT_EVER_YOU_WANT

Upvotes: 0

FogleBird
FogleBird

Reputation: 76762

That's not improper. It's a package.

http://docs.python.org/2/tutorial/modules.html#packages

package/
    __init__.py
yourmodule.py

In yourmodule.py, you can do either of the following:

import package
x = package.ClassName()

Or:

from package import ClassName
x = ClassName()

Upvotes: 8

Related Questions