Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access python package metadata from within the python console?

If I have built a python package employing distutils.core, e.g. via

setup(
    ext_package="foo",
    author="me",
    version="1.0",
    description="foo package",
    packages=["foo",],
)

where does all the metadata go (what is it intended for?) and how can I access it from within python. Specifically, how can I access the author information from the python console after doing something like

>>> import foo
like image 603
dastrobu Avatar asked Dec 19 '13 13:12

dastrobu


People also ask

How do you access packages in Python?

Create a directory and include a __init__.py file in it to tell Python that the current directory is a package. Include other sub-packages or files you want. Next, access them with the valid import statements.

What is metadata in Python package?

metadata, is a Python module for accessing and managing an item's metadata. You can explore information describing your maps and data and automate your workflows, particularly for managing standards-compliant geospatial metadata.

What is package metadata?

Package metadata describes a package for its consumers: who wrote it, where its repository is, and what versions of it have been published. It also contains a description of each version of a package present in the registry, listing its dependencies, giving the url of its tarball, and so on.


2 Answers

With python3.8 being released, you might want to use the new importlib.metadata[1] module to parse any installed package's metadata.

Getting the author information would look like this:

>>> from importlib import metadata
>>> metadata.metadata('foo')['Author']  # let's say you called your package 'foo'
'Arne'

And getting the version of your install:

>>> from importlib import metadata
>>> metadata.version('foo')
'0.1.0'

Which is a lot more straight forward than what you had to do before.


[1] Also available as backport for Python2.7 and 3.5+ as importlib-metadata, thanks to @ChrisHunt for pointing that out.

like image 155
Arne Avatar answered Oct 22 '22 22:10

Arne


One way to access the metadata is to use pip:

import pip

package = [pckg for pckg in pip.get_installed_distributions() 
            if pckg.project_name == 'package_name'][0]
#  package var will contain some metadata: version, project_name and others.

or pkg_resources

from pkg_resources import get_distribution

pkg = get_distribution('package_name')  # also contains a metadata
like image 39
Alexander Zhukov Avatar answered Oct 22 '22 21:10

Alexander Zhukov