Bob Ronaldson
Bob Ronaldson

Reputation: 11

Best way to import several classes

I have defined several classes in a single python file. My wish is to create a library with these. I would ideally like to import the library in such a way that I can use the classes without a prefix (like mylibrary.myclass() as opposed to just myclass() ), if that's what you can call them, I am not entirely sure as I am a beginner.

What is the proper way to achieve this, or the otherwise best result? Define all classes in __init __? Define them all in a single file as I currently have like AllMyClasses.py? Or should I have a separate file for every class in the library directory like FirstClass.py, SecondClass.py etc.

I realize this is a question that should be easy enough to google, but since I am still quite new to python and programming in general I haven't quite figured out what the correct keywords are for a problem in this context(such as my uncertainty about "prefix")

Upvotes: 1

Views: 111

Answers (2)

user2314737
user2314737

Reputation: 29327

If it's for your personal use, you can just put all your classes Class1, Class2, ... in a myFile.py and to use them call import myFile (without the .py extension)

import myFile

myVar1 = myFile.Class1()
myVar2 = myFile.Class2()

from within another script. If you want to be able to use the classes without the file name prefix, import the file like this:

from myFile import *

Note that the file you want to import should be in a directory where Python can find it (the same where the script is running or a directory in PYTHONPATH).

The _init_ is needed if you want to create a Python module for distribution. Here are the instructions: Distributing Python Modules

EDIT after checking the Python's style guide PEP 8 on imports:

Wildcard imports (from import) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools

So in this example you should have used

from myFile import Class1, Class2

Upvotes: 1

Guy
Guy

Reputation: 647

More information can be found in the tutorial on modules (single files) or packages (when in a directory with an __init__.py file) on the python site.

The suggested way (according to the style guide) is to spell out each class import specifically.

from my_module import MyClass1, MyClass2
object1 = MyClass1()
object2 = MyClass2()

While you can also shorten the module name:

import my_module as mo
object = mo.MyClass1()

Using from my_module import * is recommended to be avoided as it can be confusing (even if it is the recommended way for some things, like tkinter)

Upvotes: 2

Related Questions