0

I am trying to understand exactly what Python is doing to import statements and install packages. I really want to know the "path" that python follows to accomplish this so I can try and follow along to see how people who have created well known packages have accomplished it.

I created a venv called FlaskVE in a folder. Directory structure (Windows) as follows:

c:\users\me\documents\FlaskVE
     \Include
     \Lib
     \Scripts

I activated the virtual environment and installed flask using pip

$ cd c:\users\me\documents\FlaskVE\Scripts
$ activate
<-current prompt (FlaskVE) c:\users\me\documents\FlaskVE\Scripts
$ pip install flask
$ python
$ from flask import Flask

At this point, python looks along my PATH for python packages, since I am in a venv, the PATH points to the current folder I am in. Within \FlaskVE\Lib\site-packages\flask there is not a Flask.py folder. How does Python find the Flask class? I can see within the init.py file within \FlaskVE\Lib\site-packages\flask there is a command "from .app import Flask, Request, Response" and within the app.py file in that directory there is a class called Flask. Is this the one it is importing and if so, does the "from flask" call start the init.py file automatically?

chris dorn
  • 817
  • 8
  • 13
  • The `flask` **directory** is a package. The presence of the `__init__.py` file makes it a package. You may want to read up first on how those work in the [Python tutorial](https://docs.python.org/3/tutorial/modules.html#packages). – Martijn Pieters Jun 30 '17 at 14:04
  • 1
    And yes, importing a package will load the `__init__.py` file for that package. – Martijn Pieters Jun 30 '17 at 14:05
  • Thank you. So whether it says from or import, the __init__.py file is loaded from that directory? – chris dorn Jun 30 '17 at 15:43
  • 1
    It doesn't matter if you use `from ... import` or just `import`; the only difference there is what is bound into your current namespace. Both load packages exactly the same way, and yes, when you import `foobar` and `foobar` is a directory with an `__init__.py` file, then that file will be executed to satisfy the import. – Martijn Pieters Jun 30 '17 at 17:24

0 Answers0