In Python, is it good to import all attributes using a template?

and why?

Sometimes I need to import all the attributes of a module, so I use the import of wildcards, but one of my Vim scripts (using flake8 as a syntax check) always gives me a warning and says that I cannot find undefined names.

Are there any other disadvantages of using wildcard import?

+1
source share
5 answers

Generally not recommended from module import *. Importing wildcards pollutes the namespace; You have imported more names than you need, and if you accidentally reference an imported name, you cannot get the name you want.

, , , :

from foo import bar
from spam import *

spam spam.bar, foo.bar .

+4

:

foo.py

import sys
os = sys # just for the fun of it... :-D

python

>>> import os
>>> from foo import *
>>> os.path.join('p1', 'p2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

. .

*, , .

+3

, PyDocs:

, *, - ​​ .

+2

, , , script, - :

.   

package.x

.

0

Martijn , , - , ... .

:

#foo.py
from bar import *
from baz import *
from qux import *

def breakfast(x):
    with corn_beef_hash(x) as yummy:
        for egg in yummy:
            yield ham(egg.scrambled)

Now, after a few months, you cannot remember what it actually does corn_beef_hash, so you look at the documentation, except that you cannot remember whether it was corn_beef_hashpart baror bazor qux. This makes tracking difficult. Also, if you know where the function was originally defined, this gives you some clues about what it should do, which may make it easier to read the code.

0
source

All Articles