Timur U
Timur U

Reputation: 445

More elegant way to switch tqdm progress bars without LSP Pyright error

I'm creating a custom Python CLI module using docx2pdf.

The docx2pdf module is using tqdm to display progress bars while the .docx files are being converted to .pdf.

In my module I'm using the CLI log parameter to enable/disable console logging output.

Switching progress bar output with tqdm is explained in Stack Overflow and GitHub posts:

According to this information I'm adding the switch tqdm function:

from functools import partialmethod
from tqdm import tqdm

def tqdm_log(log: bool = False) -> None:
    ''' tqdm logging switch '''
    if not log:
        tqdm.__init__ = partialmethod(tqdm.__init__, disable=True)

It works correctly, but the LSP pyright module returns an error when using functools.partialmethod with tqdm.__init__:

Cannot assign member "__init__" for type "type [tqdm [_T@tqdm]]"...

Is there any way to make this code more elegant and/or resolve the LSP pyright error?

Screenshot of the LSP pyright error

Upvotes: 5

Views: 1029

Answers (1)

Jonathan Feenstra
Jonathan Feenstra

Reputation: 2779

Since version 4.66.0, the default tqdm parameters can be overridden using environment variables with the TQDM_-prefix followed by the parameter name in uppercase. This means you can globally disable tqdm output by setting the TQDM_DISABLE environment variable to 1 before importing tqdm or any packages that use it.

First, make sure you are using a version of tqdm that supports this:

python -m pip install "tqdm>=4.66.0"  

Then before importing tqdm or any packages that use it (such as docx2pdf), add the following:

import os

# Get the log CLI argument here

if not log:
    os.environ["TQDM_DISABLE"] = "1"

# import other packages like docx2pdf here

However, whether this is really a more elegant solution is debatable, since PEP 8 states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

Having imports after the part where you set the environment variable would violate this guideline.

In my opinion, your current solution is already acceptable and you can ignore/disable the Pyright warning. In that case it may also be a good idea to leave a comment explaining why the warning is safe to ignore here.

Upvotes: 1

Related Questions