Importing files in Python from __init__.py

前端 未结 3 839
迷失自我
迷失自我 2020-12-28 20:32

Suppose I have the following structure:

app/
  __init__.py
  foo/
    a.py
    b.py
    c.py
    __init__.py

a.py, b.py and c.py share some

相关标签:
3条回答
  • 2020-12-28 20:53

    Yes, but don't do it. Seriously, don't. But if you still want to know how to do it, it'd look like this:

    import __init__
    
    re = __init__.re
    logging = __init__.logging
    os = __init__.os
    

    I say not to do it not only because it's messy and pointless, but also because your package isn't really supposed to use __init__.py like that. It's package initialization code.

    0 讨论(0)
  • 2020-12-28 20:55

    No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass logging around as a function argument, which would be a weird way to do things, to say the least).

    But the modules are only imported once anyway (and then put into the a, b, and c namespaces), so don't worry about using too much memory or something like that.

    You can of course put them into a separate module and import that into each a, b, and c, but this separate module would still have to be imported everytime.

    0 讨论(0)
  • 2020-12-28 21:03

    You can do this using a common file such as include.py, but it goes against recommended practices because it involves a wildcard import. Consider the following files:

    app/
        __init__.py
    foo/
        a.py
        b.py
        c.py
        include.py <- put the includes here.
        __init__.py
    

    Now, in a.py, etc., do:

    from include import *
    

    As stated above, it's not recommended because wildcard-imports are discouraged.

    0 讨论(0)
提交回复
热议问题