Importing from within package

Chris Angelico rosuav at gmail.com
Wed Sep 23 00:23:07 EDT 2020


On Wed, Sep 23, 2020 at 2:16 PM Terry Reedy <tjreedy at udel.edu> wrote:
>
> On 9/22/2020 8:31 PM, Chris Angelico wrote:
> > On Wed, Sep 23, 2020 at 9:24 AM Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
> >>
> >> On Tue, 22 Sep 2020 20:14:01 +0400, Abdur-Rahmaan Janhangeer
> >> <arj.python at gmail.com> declaimed the following:
> >>
> >>> I have this main script:
> >>> https://github.com/Abdur-rahmaanJ/shopyo/blob/dev/shopyo/__main__.py
> >>>
> >>
> >>          Well, that file name scares me...
> >>
> >>          __main__ is the name Python uses internally for the, well, main program
> >> (whatever the real file name is), and becomes part of the convention
> >>
> >> if __name__ == "__main__":
> >>          #running as stand-alone program
> >>          #do stuff
> >>
> >> where imported files will appear with the name by which they were imported.
> >>
> >
> > In a package, __main__.py does that same job.
>
> I am not sure of your intended meaning.
>
> Assume that director 'mypac' is in a directory on sys.path.  Forget
> namespace packages, which I have not studied.
> 'import mypac' within code imports mypac/__init__.py
> 'python -m mypac' on a command line runs mypac/__main__.py
>
> Example: .../pythonxy/lib/idlelib. lib is on sys.path.
> idlelib/__init__.py is nearly empty.
> idlelib/__main__.py starts IDLE,
> so 'python -m idlelib' on a command line starts idle.
>

Correct. I was a bit too brief there, but Terry's elaboration is what
I was getting at: that __main__.py is a valid and normal member of a
package, and will be used as the entry point.

ChrisA


More information about the Python-list mailing list