英文:
Type hint pytz timezone
问题
我有一个返回 pytz.timezone('...')
对象的函数。例如,对于下面的函数,返回的类型提示应该是什么?
def myfunc(tz_str: str) -> ????:
return pytz.timezone(tz_str)
一般来说,我们应该如何为已安装模块中的对象提供类型提示?
英文:
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?
答案1
得分: 2
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')
英文:
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')
答案2
得分: 0
Since you have hard-coded the argument to timezone
, you know that the result will be an instance of pytz.UTC
.
def myfunc() -> pytz.UTC:
return pytz.timezone('UTC')
If the argument isn't known until runtime, for example,
def myfunc(tz: str) -> ...:
return pytz.timezone(tz)
the best you could do is use the same return type as is defined for timezone
itself, which can be found in the Typeshed. (The stub file appears to define parts of the type in the stub itself, rather than using types defined in the actual library. I did not dig into the source code to see exactly what should be used or how; I leave that as an exercise for the reader.)
英文:
Since you have hard-coded the argument to timezone
, you know that the result will be an instance of pytz.UTC
.
def myfunc() -> pytz.UTC:
return pytz.timezone('UTC')
If the argument isn't know until runtime, for example,
def myfunc(tz: str) -> ...:
return pytz.timezone(tz)
the best you could do is use the same return type as is defined for timezone
itself, which can be found in the Typeshed. (The stub file appears to define parts of the type in the stub itself, rather than using types defined in the actual library. I did not dig into the source code to see exactly what should be used or how; I leave that as an exercise for the reader.)
答案3
得分: 0
从代码中提取的内容翻译如下:
from typing import Type, Union
from pytz.tzinfo import DstTzInfo, StaticTzInfo
class _UTCclass:
pass
TzInfo = Union[_UTCclass, StaticTzInfo, DstTzInfo]
def myfunc(tz_str: str) -> TzInfo:
return pytz.timezone(tz_str)
有点凌乱,但能完成任务。
英文:
Do this,
from typing import Type, Union
from pytz.tzinfo import DstTzInfo, StaticTzInfo
class _UTCclass:
pass
TzInfo = Union[_UTCclass, StaticTzInfo, DstTzInfo]
def myfunc(tz_str: str) -> TzInfo:
return pytz.timezone(tz_str)
A bit ugly, but does the job.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论