Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is the idiom "from Module import ClassName" typical?

Tags:

python

import

Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py.

Within a package, if another module needs to instanciate an object of class ToolSet, I use:

from ToolSet import ToolSet
...
toolSet = ToolSet()

instead of:

import ToolSet
...
toolSet = ToolSet.ToolSet()

I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)

Is this a correct idiom?

Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py for that package. For example, if ToolSet is in package UI and I want to expose it, I would put the following in UI/__init__.py :

from ToolSet import ToolSet

So that, from an external module I can write

import UI
...
toolSet = UI.ToolSet()

Again, is this pythonic?

like image 552
Philippe Beaudoin Avatar asked Nov 16 '25 07:11

Philippe Beaudoin


1 Answers

To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide

it's okay to say this though:

from subprocess import Popen, PIPE

I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.

Eg suppose the module Thing doesn't have a Thyng member

from Thing import Thyng

Goes wrong immediately you run the .py file, whereas

import Thing
# ...
def fn():
    Thing.Thyng()

Doesn't go wrong until you run fn()

As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py and implementation files. Importing things into the __init__.py keeps the interface the same. It is common practice in the standard libraries too.

like image 185
Nick Craig-Wood Avatar answered Nov 18 '25 20:11

Nick Craig-Wood