سؤال

This question seems to be pretty obvious, but I cannot find any satisfactory answer...

So, I have a package named notes in a location known by PYTHONPATH, where I would like the main module to be called per the package:

my_python_scripts/
 +-- notes/
      +-- __init__.py
      +-- notes.py        <-- this is the main module, containing a main() function
      +-- main_window.py
      +-- main_window.ui

The aim behind is to use it this way:

import notes
notes.main()

but in this case, I only get the following error:

Traceback (most recent call last):
  File "C:\Users\xxxx\notes_launcher.py", line 13, in <module>
    notes.main()
AttributeError: 'module' object has no attribute 'main'

Currently, I know how to make it work differently:

  • either by calling the full hierarchy, which is a bit annoying and seems a bet weird to me (as the well-known from datetime import datetime):

    from notes import notes
    notes.main()
    
  • or by tweaking content of the __init__.py (but everyone seems to agree on leaving this file empty):

    from notes import main
    

So, how could I do that? Should I even be dreaming of that?

هل كانت مفيدة؟

المحلول

You can even do from notes.notes import * in __init__.py, or simply place the contents of notes.py into __init__.py and do without notes.py. People do both and there's no really pressing reason not to, as far as I know.

نصائح أخرى

For me the right way is to put what necessary in the __init__.py file. I see nothing bad with that. It's there for that - to do what initializations you want with your package. So if you design your package to be used simply like import notes the __init__.py file seems to me like the right place for that.

Systems like OpenERP for instance use massively this technique. Modules in OpenERP are Python packages which import in their __init__.py file all the sub-modules like report, wizard etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top