Skip to content

Instantly share code, notes, and snippets.

@Justintime50
Created September 23, 2021 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Justintime50/079a9e287d8afa1ae78773ae373f7829 to your computer and use it in GitHub Desktop.
Save Justintime50/079a9e287d8afa1ae78773ae373f7829 to your computer and use it in GitHub Desktop.
Learn how to package non-Python assets into your Python Package

Package non-Python Assets into your Python Package

There are times where you may need to include non-Python assets in your Python package for distribution. This may include data files or JSON assets from a submodule for example that your Python package needs to reference. By default, Python will not include these assets in the bdist/sdist. You can either include an empty __init__.py file in that submodule (even if the project isn't Python) and rely on the magic of packages=setuptools.find_packages() in setup.py or you can explicitly include those non-Python assets by using the following steps.

  1. In setup.py, include an array of locations to include. These are glob matching patterns. An example of this looks like the following:
package_data={
    'top_level_package': [
        'path/to/assets/one/*.json',
        'path/to/assets/two/*.json',
    ],
},
  1. Now to properly reference these JSON files, you need to use pkg_resources, otherwise your package won't be able to properly find the assets (relative or full path):
data_file = pkg_resources.resource_stream('top_level_package', 'path/to/asset')
json_data = json.load(data_file)
print(json_data)

Additional Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment