Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid double typing class names in python

Tags:

python

This seems like a silly question but I haven't been able to come across the answer anywhere. Within my various packages I have a set of modules, usually each containing one class. When I want to create an instance of a class I have to refer to 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 such that I don't have to type the name twice? Ideally I'd like to just have to type package.obj().

like image 691
sfpiano Avatar asked Sep 25 '13 16:09

sfpiano


3 Answers

Python is not Java. Feel free to put many classes into 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 you want them in separate files to ease the maintenance burden, that's fine, but you should not then inflict extra pain on your users (or yourself, if you use your own package ;). Gather your public classes in the package's __init__ file (or a category file, such as image) to present a fairly flat namespace:

mypackage's __init__.py (or image.py):

from _jpeg import jpeg
from _png import png

mypackage's _jpeg.py:

class jpeg(...):
    ...

mypackage's _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(....)
like image 66
Ethan Furman Avatar answered Oct 02 '22 16:10

Ethan Furman


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

from package.obj import obj
my_obj = obj()
like image 33
falsetru Avatar answered Oct 02 '22 16:10

falsetru


Give your classes and modules meaningful names. That's the way. Name your module 'classes' and name your class 'MyClass'.

from package.classes import MyClass

myobj = MyClass()
like image 26
Andreas Jung Avatar answered Oct 02 '22 16:10

Andreas Jung