Is Python a typical "from class importName" identity?

Since I prefer small files, I usually put one "public" class in a Python module. I call the module with the same name as the class that it contains. So, for example, the class ToolSetwill be defined in ToolSet.py.

Inside the package, if another module needs to create an object of the ToolSet class, I use:

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

instead:

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

I do this to reduce stuttering (I prefer to stutter at the top of the file than in my code.)

Is this the correct idiom?

Here is a related question. Inside the package, I often have a small number of classes that I would like to expose to the outside world. They are imported internally __init__.pyfor this package. For example, if it ToolSetis in a package UIand I want to expose it, I would put the following in UI/__init__.py:

from ToolSet import ToolSet

So, from the external module I can write

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

Again, is this pythonic?

+3
source share
4 answers

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

It’s good to say this though:

from import subprocess Popen, PIPE

, , - , (, ), , , .

, , Thing Thyng

from Thing import Thyng

.py,

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

, fn()

, , . , large.py __init__.py . __init__.py . .

+5

. , , Python.

from module import name , datetime, , . , ORM .

import module ( os os.path) , (, database.session cherrypy.session ) , , .

, (, import os.path), , .

0
0

from itertools import chain, ifilter, islice, izip , , , , , .

Once, in a frenzy of erroneous correctness, I went through a large block of code and replaced it from datetime import datetimewith import datetime. It was a good example of Mark Twain's observation that a person who raises a rat by the tail will learn something that cannot be known otherwise. This, of course, put me directly on the question of why it is normal to use from x import y.

0
source

Source: https://habr.com/ru/post/1724535/


All Articles