In Python, is it a good practice to import all attributes with a wildcard?

前端 未结 5 1658
清歌不尽
清歌不尽 2020-12-21 06:48

and why?

Sometimes I need import all the attributes of a module so I use wildcard importing, but one of my Vim scripts(using flake8 as its syntax checker) always giv

5条回答
  •  别那么骄傲
    2020-12-21 07:00

    Using the wildcard import can cause subtle bugs:

    foo.py

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

    python console

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

    This is especially important when updating library versions. They might or might not add new variables and break your code in horrible ways.

    If you really want to use the * import always place it first so that other imports and definitions take precedence.

提交回复
热议问题