Alexander Engelhardt
Alexander Engelhardt

Reputation: 1712

How to allow excluding a module when importing my Python package?

I wrote a Python package pack that can perform a set of related tasks, taskA, taskB, ..., taskZ. Each of them has its own module file, e.g. taskN.py.

Now say in taskN.py I import a third party package evilpack. It Works On My Machine™, but a coworker of mine (a) can't install evilpack, but (b) does not even need that module taskN.

My goal is to structure my package so that we can choose at import time whether we want to load the module taskN or ignore it.

What's the most elegant way to solve this? I'm sensing it has something to do with the directories' __init__.py files.

Upvotes: 0

Views: 2398

Answers (2)

BoarGules
BoarGules

Reputation: 16942

A simple way to solve this problem:

Identify all of the modules that may have unfulfilled dependencies.

In the main module that does the importing, surround each such import with a try...except clause:

try:
    import packN
except ImportError as details:
    print ("Could not import packN because of this error:", details)
    print ("Functionality xxxx will not be available")
    packN = None

If your colleague's code doesn't call a function that relies on packN then all will be well.

Upvotes: 1

ycx
ycx

Reputation: 3211

I think I can only point you in the correct direction via setupscript because I do not have access to your data/package details.

To simply put, you will have to locate your taskN.py's setup.py script, and specifically remove the module from inside the script.

Upvotes: 0

Related Questions