Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint pytz timezone

I have a function that returns a pytz.timezone('...') object. For example for the function below, what should be the type hint for the return?

def myfunc(tz_str: str) -> ????:
  return pytz.timezone(tz_str)

And in general, how should we type hint objects from installed modules?

like image 504
masec Avatar asked Feb 23 '26 23:02

masec


2 Answers

Faced with such a problem after starting using mypy

. To resolve this use types-pytz - this repository with stubs for pytz:

  • pip install types-pytz
import pytz
from pytz.tzinfo import DstTzInfo
def get_timezone() -> DstTzInfo:
   return pytz.timezone('UTC')
like image 165
MAXIM SUBBOTIN Avatar answered Feb 25 '26 13:02

MAXIM SUBBOTIN


BaseTzInfo works for me since they all seem to derive from that. It isn't exactly the same as the Union, but works.

def myfunc(tz: str) -> pytz.tzinfo.BaseTzInfo:
   return pytztimezone(tz)
like image 26
rrauenza Avatar answered Feb 25 '26 11:02

rrauenza