What is the correct way to share package version with setup.py and the package?

后端 未结 7 1790
盖世英雄少女心
盖世英雄少女心 2020-12-07 08:42

With distutils, setuptools, etc. a package version is specified in setup.py:

# file: setup.py
...
setup(
name=\'foobar         


        
7条回答
  •  余生分开走
    2020-12-07 09:03

    Set the version in setup.py only, and read your own version with pkg_resources, effectively querying the setuptools metadata:

    file: setup.py

    setup(
        name='foobar',
        version='1.0.0',
        # other attributes
    )
    

    file: __init__.py

    from pkg_resources import get_distribution
    
    __version__ = get_distribution('foobar').version
    

    To make this work in all cases, where you could end up running this without having installed it, test for DistributionNotFound and the distribution location:

    from pkg_resources import get_distribution, DistributionNotFound
    import os.path
    
    try:
        _dist = get_distribution('foobar')
        # Normalize case for Windows systems
        dist_loc = os.path.normcase(_dist.location)
        here = os.path.normcase(__file__)
        if not here.startswith(os.path.join(dist_loc, 'foobar')):
            # not installed, but there is another version that *is*
            raise DistributionNotFound
    except DistributionNotFound:
        __version__ = 'Please install this project with setup.py'
    else:
        __version__ = _dist.version
    

提交回复
热议问题