from … import OR import … as for modules

后端 未结 6 463
萌比男神i
萌比男神i 2020-11-29 02:57

Should I use

from foo import bar

OR

import foo.bar as bar

when importing a module and an

6条回答
  •  孤城傲影
    2020-11-29 03:19

    This is a late answer, arising from what is the difference between 'import a.b as b' and 'from a import b' in python

    This question has been flagged as a duplicate, but there is an important difference between the two mechanisms that has not been addressed by others.

    from foo import bar imports any object called bar from namespace foo into the current namespace.

    import foo.bar as bar imports an importable object (package/module/namespace) called foo.bar and gives it the alias bar.

    What's the difference?

    Take a directory (package) called foo which has an __init__.py containing:

    # foo.__init__.py
    class myclass:
        def __init__(self, var):
            self.__var = var
    
        def __str__(self):
            return str(self.__var)
    
    bar = myclass(42)
    

    Meanwhile, there is also a module in foo called bar.py.

    from foo import bar
    print(bar)
    

    Gives:

    42
    

    Whereas:

    import  foo.bar as bar
    print(bar)
    

    Gives:

    
    

    So it can be seen that import foo.bar as bar is safer.

提交回复
热议问题