Adding code to __init__.py

后端 未结 3 1794
独厮守ぢ
独厮守ぢ 2020-12-02 05:09

I\'m taking a look at how the model system in django works and I noticed something that I don\'t understand.

I know that you create an empty __init__.py

3条回答
  •  我在风中等你
    2020-12-02 05:29

    All imports in __init__.py are made available when you import the package (directory) that contains it.

    Example:

    ./dir/__init__.py:

    import something
    

    ./test.py:

    import dir
    # can now use dir.something
    

    EDIT: forgot to mention, the code in __init__.py runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.

    EDIT2: dgrant pointed out to a possible confusion in my example. In __init__.py import something can import any module, not necessary from the package. For example, we can replace it with import datetime, then in our top level test.py both of these snippets will work:

    import dir
    print dir.datetime.datetime.now()
    

    and

    import dir.some_module_in_dir
    print dir.datetime.datetime.now()
    

    The bottom line is: all names assigned in __init__.py, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.

提交回复
热议问题