Search code examples
pythonpython-importpython-packagingpyproject.toml

What defines the import statement of python package?


I have plenty of home-developed packages on Gitlab. Many of these package have setup.py but many of them don't.

I also have projects on Gitlab that use these packages.

My duty is to map the imports in all of these projects to the corresponding package. The problem is that most of the time, the packages that don't have setup.py have a project name slightly different from the statement used in the import

Example:

  • project called: abc-def, or abc def
  • when installing: pip install company-name-abc-def
  • when importing: abc_def

Sometimes the name could be further (not only a dash or space)

Is there a way to know the import name for each project? or the project name from the import statement?

Could it be something set in the pyproject.toml? I read these files but there wasn't something obvious of this.


Solution

  • You're talking about the difference between distributions (distribution packages) and import packages. The names of the two are completely unrelated. There's no way to derive one from the other, unless a project decides to make them similar. Also note that a distribution can contain any number of import packages, which makes deriving a mapping between the two more challenging.

    Broadly speaking, the distribution name is what you specify in your build system metadata (e.g. a name = "my-distribution" line in pyproject.toml) while the import package name is determined by the actual directory / file name in your package's source tree.

    The distribution name is used when specifying dependencies to your build system (e.g. when invoking pip install or in your build system's dependencies table in pyproject.toml) while the import package name only appears in import statements.