Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Define a function only if package exists

Tags:

python

Is it possible to tell Python 2.7 to only parse a function definition if a package exists?

I have a script that is run on multiple machines. There are some functions defined in the script that are very nice to have, but aren't required for the core operations the script performs. Some of the machines the script is run on don't have the package that the function imports, (and the package can't be installed on them). Currently I have to comment out the function definition before cloning the repo onto those machines. Another solution would be to maintain two different branches but that is even more tedious. Is there a solution that prevents us from having to constantly comment out code before pushing?

There are already solutions for when the function is called, such as this:

try:
    someFunction()
except NameError:
    print("someFunction() not found.")
like image 314
John Avatar asked Sep 05 '15 14:09

John


People also ask

How do you make a function a parameter in Python?

Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. Add statements that the functions should execute.

How can we pass parameters in user defined functions in Python?

The function may take arguments(s) also called parameters as input within the opening and closing parentheses, just after the function name followed by a colon.


2 Answers

Function definitions and imports are just code in Python, and like other code, you can wrap them in a try:

try:
    import bandana
except ImportError:
    pass  # Hat-wearing functions are optional
else:
    def wear(hat):
        bandana.check(hat)
        ...

This would define the wear function only if the bandana module is available.

Whether this is a good idea or not is up to you - I think it would be fine in your own scripts, but you might not want to do this in code other people will use. Another idea might be to do something like this:

def wear(hat):
    try:
        import bandana
    except ImportError:
        raise NotImplementedError("You need the bandana package to wear hats")
    else:
        bandana.check(hat)
        ...

This would make it clearer why you can't use the wear function.

like image 133
Wander Nauta Avatar answered Sep 27 '22 20:09

Wander Nauta


A somewhat improved solution is as follows: In file header:

try:
    # Optional dependency
    import psutil
except ImportError as e:
    psutil = e

Later in the beginning of your function or inside __init__ method:

if isinstance(psutil, ImportError):
    raise psutil

Pros: you get the original exception message when you access optional functionality. Just as if you've did simply import psutil

like image 42
Viacheslav Kroilov Avatar answered Sep 27 '22 22:09

Viacheslav Kroilov