Skip to main content

Import something if it exists.

Project description

Usage

This library contains only the context manager optional_import:

>>> from optional_import import optional_import

A successful import works as usual:

>>> with optional_import():
...     import collections
>>> type(collections)
<type 'module'>

If the import does not exist, optional_import suppresses the ImportError that would otherwise be raised.

>>> import unicorns
Traceback (most recent call last):
  ...
ImportError: No module named unicorns

>>> with optional_import():
...     import unicorns

>>> unicorns
Traceback (most recent call last):
  ...
NameError: name 'unicorns' is not defined

Example: Django local settings

A common pattern in Django is to put default settings in settings.py, put optional site-specific settings in settings_local.py, and import * from the local settings file if it exists.

with optional_import():
    from .settings_local import *

Why not just catch ImportError?

Optional imports can almost be achieved simply by catching ImportError:

try:
    import foo
except ImportError:
    pass

But this approach introduces a problem: If foo exists but raises ImportError, we want that error to be raised, but instead it is swallowed by the except clause.

With optional_import, the error is raised as desired. In the following example, the bad module tries to import a nonexistent package unicorns:

>>> with optional_import():
...     import bad
Traceback (most recent call last):
  ...
ImportError: No module named unicorns

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

optional_import-1.2.tar.gz (2.4 kB view details)

Uploaded Source

File details

Details for the file optional_import-1.2.tar.gz.

File metadata

  • Download URL: optional_import-1.2.tar.gz
  • Upload date:
  • Size: 2.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for optional_import-1.2.tar.gz
Algorithm Hash digest
SHA256 cd651eb9824a93d586905a4c54c19a9f2865f59201b022dcd32a8fc71f1faf86
MD5 eccd26664b97e9db881e161a458a67dd
BLAKE2b-256 dec6cbbda50cb62ade7d16acaaa5d1b1a34589281ee8b24d54ba36d5d6d35811

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page