Avoid double typing class names in python

This seems like a silly question, but I couldn’t find the answer anywhere. In my various packages I have a set of modules, each of which contains one class. When I want to instantiate a class, I have to reference it twice:

Example: package /obj.py:

class obj(object): pass 

file.py:

 import package.obj my_obj = package.obj.obj() 

Is there a way to reorganize my code in such a way that I don't need to enter the name twice? Ideally, I would just need to type package.obj ().

+8
python
source share
3 answers

Python is not Java. Feel free to put many classes in one file, and then name the file according to the category:

 import mypackage.image this_image = image.png(...) that_image = image.jpeg(....) 

If your classes are so large that you want them to be in separate files to ease the maintenance burden, that's fine, but you shouldn't hurt your users (or yourself if you use your own package;). Collect your public classes in the __init__ package file (or in the category file, for example, in image ) to represent a fairly flat namespace:

mypackage __init__.py (or image.py ):

 from _jpeg import jpeg from _png import png 

mypackage _jpeg.py :

 class jpeg(...): ... 

mypackage _png.py :

 class png(...): ... 

user code:

 # if gathered in __init__ import mypackage this_image = mypackage.png(...) that_image = mypackage.jpeg(...) 

or:

 # if gathered in image.py from mypackage import image this_image = image.png(...) that_image = image.jpeg(....) 
+8
source share

You can use the from ... import ... statement:

 from package.obj import obj my_obj = obj() 
+5
source share

Give your classes and modules meaningful names. This is the way. Name your module “classes” and name your class “MyClass”.

 from package.classes import MyClass myobj = MyClass() 
+1
source share

All Articles