Is there a point to import the same module in two different ways in a program?

后端 未结 4 1180
礼貌的吻别
礼貌的吻别 2021-01-23 00:19

Is there a point to import as both wildcard and non-wildcard manner like:

import spam as sp
from spam import *

in the very same file?<

4条回答
  •  遥遥无期
    2021-01-23 01:13

    import spam as sp will load the module and put it into the variable sp. from spam import * will load the module and all its attributes (classes, functions, etc...) and also the ones that are imported with a wildcard into spam will be accessible.

    import * is a shortcut when you have a lot of classes, functions you need to access. But it is a bad practice (cf PEP) since you do not encapsulate imported attributes into a namespace (and it's what you do with import spam as sp) and can lead to unwanted behavior (if 2 functions have the same name in your main program and into spam)

    The best practice, and what states clearly what you'll use is from spam import func1, func2 or if you will use it a lot import spam as sp and use sp.func1()

提交回复
热议问题