check if current python code is running from package

is it possible to detect if current python code is running from package?

if yes – is it possible to get package metadata (name, version, description)?


package is created with this kind of setup.py

import os
from setuptools import setup, find_packages
setup(
    name='my-pack-name',
    description='my description ' + os.getenv('GIT_COMMIT', '*')[:7],
    version=os.getenv('BUILD_VERSION', '0.0.0dev'),
    packages=find_packages(),
)

build: python3 setup.py bdist_wheel -d ./artifact

install on target: pip3 install "my-pack-name-x.x.x.whl" --upgrade

now from my_pack_name/app.py that was inside my-pack-name-x.x.x.whl i want to detect that i’m running from installed package

and if so then get package metadata defined during setup.py execution

Answer

For Python >=3.8

https://docs.python.org/es/3.10/library/importlib.metadata.html

You can get the metadata for a package by:

from importlib.metadata import metadata

md = metadata("your package name")
author = md["Author"]
# etc ...

For Python <3.8

This is just an idea (not tested).

What about having the package metadata in a different module, and try relative import it in the app.py module?

# metadata.py
name='my-pack-name',
description='my description ' + os.getenv('GIT_COMMIT', '*')[:7],
version=os.getenv('BUILD_VERSION', '0.0.0dev')

In setup.py you could reuse that:

# setup.py
import os
from setuptools import setup, find_packages
import .metadata as md
setup(
    name=md.name,
    description=md.description + os.getenv('GIT_COMMIT', '*')[:7],
    version=md.version,
    packages=find_packages(),
)

And the in app.py

def get_metadata():
    try:
        import .metadata as md
    except ImportError:
        return None
    else:
        # return metadata here

That way if get_metadata returns None, you were not able to import the module, so you’re not executing the app.py in your package, otherwise, you are in your package and as a bonus you got your metadata.