Create a pass-through for an installed module to achieve an optional import

2024/10/11 12:31:48

I'm writing a library in python 3.7. I'd like it to have as few dependencies as possible. For example, tqdm is nice to have but ideally I'd like my library to work without it if it's not there. Therefore, wherever a script in my library has, for example:

from tqdm import tqdmdef a_function():for x in tqdm([1, 2, 3]):...

I would want it to use the real tqdm if it's installed but otherwise just act as if it wasn't there. So I created a script inside the library called tqdm.py, containing a pass-through function, which defaults to being a dummy function if it fails to import tqdm:

try:from tqdm import tqdm as tqdmExtdef tqdm(function, **kwargs):return tqdmExt(function, **kwargs)except ModuleNotFoundError:def tqdm(function, **kwargs):return function(**kwargs)

So then, my first step when using the library is to add the path to the library itself at the front of the system path, so:

import sys
sys.path.insert(0, 'path_to_library')

Then I hoped to import the library function, which would then pick up the local tqdm function. Unfortunately this doesn't work, because now the script in my library can't be imported because it, too, sees its own library at the front of the path, and fails when trying to import the local tqdm (it would really need to pick up the installed tqdm):

from tqdm import tqdm as tqdmExtImportError: cannot import name 'tqdm' from 'tqdm'

Any ideas how to get this working, or another way to achieve this optional dependency?

Answer

Thanks very much for your input. In particular Michael Butscher allowed me to arrive at this even simpler solution. Since in python 3, installed modules are picked up before local modules unless you actively insert local modules at the beginning of the path, I stop thinking about my script being the default that should pass through the original import, and rather just let it lie in my library as something that gets picked up as a fallback in case the original dependency is not installed. So practically, I have in my library a script called tqdm.py containing only:

def tqdm(*args):if len(args) == 1:return args[0]else:return Pbar()class Pbar():def update(*args):return None

This is a minimum which allows the calls I make to tqdm functionality within the library to not fail, although the user doesn't actually get the progress bars that they would do if the dependency were installed.

https://en.xdnf.cn/q/118326.html

Related Q&A

Django, Redis: Where to put connection-code

I have to query redis on every request in my Django-app. Where can I put the setup/ connection routine (r = redis.Redis(host=localhost, port=6379)) so that I can access and reuse the connection without…

Events and Bindings in tkinter does not work in loop

I am trying to create binding in a loop using tkinter module.from tkinter import * class Gui(Frame):def __init__(self, parent):Frame.__init__(self, parent) self.parent = parentself.initUI()def Arrays(…

Python Machine Learning Algorithm to Recognize Known Events

I have two sets of data. These data are logged voltages of two points A and B in a circuit. Voltage A is the main component of the circuit, and B is a sub-circuit. Every positive voltage in B is (1) co…

How can I replace Unicode characters in Python?

Im pulling Twitter data via their API and one of the tweets has a special character (the right apostrophe) and I keep getting an error saying that Python cant map or character map the character. Ive lo…

Filtering Pandas DataFrame using a condition on column values that are numpy arrays

I have a Pandas DataFrame called dt, which has two columns called A and B. The values of column B are numpy arrays; Something like this: index A B 0 a [1,2,3] 1 b [2,3,4] 2 c …

Creation a tridiagonal block matrix in python [duplicate]

This question already has answers here:Block tridiagonal matrix python(9 answers)Closed 6 years ago.How can I create this matrix using python ? Ive already created S , T , X ,W ,Y and Z as well as the…

Python tkinter checkbutton value always equal to 0

I put the checkbutton on the text widget, but everytime I select a checkbutton, the function checkbutton_value is called, and it returns 0.Part of the code is :def callback():file_name=askopenfilename(…

How does derived class arguments work in Python?

I am having difficulty understanding one thing in Python.I have been coding in Python from a very long time but theres is something that just struck me today which i struggle to understandSo the situat…

grouping on tems in a list in python

I have 60 records with a column "skillsList" "("skillsList" is a list of skills) and "IdNo". I want to find out how many "IdNos" have a skill in common.How …

How do I show a suffix to user input in Python?

I want a percentage sign to display after the users enters their number. Thankspercent_tip = float(input(" Please Enter the percent of the tip:")("%"))For example, before the user t…