我创建了一个日期数据框,如下所示:
import pandas as pd
timespan = 366
df = pd.DataFrame({'Date':pd.date_range(pd.datetime.today(), periods=timespan).tolist()})
Run Code Online (Sandbox Code Playgroud)
我正在努力确定季度中的天数。例如
date expected_value
2017-01-01 1 # First day in Q1
2017-01-02 2 # Second day in Q1
2017-02-01 32 # 32nd day in Q1
2017-04-01 1 # First day in Q2
Run Code Online (Sandbox Code Playgroud)
我可以听听你的建议吗?先感谢您。
我想知道如何使这个 getter 更加类型安全:
VALUES = {
'1': 'One',
'2': 'Two',
'3': 'Three'
}
def get(key : str) -> str:
return VALUES[key]
Run Code Online (Sandbox Code Playgroud)
str我希望有一个keyof VALUESand类型,而不是类型type(VALUES[key])。
get('4')应该抛出无效类型警告,因为该键不存在。不确定这对于 Python 是否可行,因为我确实生活在 TypeScript 仙境中......:-)
TypeScript 正确的样子应该是这样的:
VALUES = {
'1': 'One',
'2': 'Two',
'3': 'Three'
}
def get(key : str) -> str:
return VALUES[key]
Run Code Online (Sandbox Code Playgroud) 我遇到了这个静态类型提示不匹配(使用 Pyright):
from __future__ import annotations
from typing import AnyStr, Iterable
def foo(i: Iterable[AnyStr]):
return i
def bar(i: Iterable[str] | Iterable[bytes]):
return i
def baz(i: Iterable[str | bytes]):
return i
def main():
s = ['a']
# makes sense to me
baz(foo(s)) # allowed
foo(baz(s)) # not allowed
# makes sense to me
baz(bar(s)) # allowed
bar(baz(s)) # not allowed
bar(foo(s)) # allowed
foo(bar(s)) # nope -- why?
Run Code Online (Sandbox Code Playgroud)
什么之间的区别Iterable[AnyStr]和Iterable[str] | Iterable[bytes]?
它们不应该是“等效的”吗?(除了AnyStr在上下文中引用单个一致类型)
更具体地说:键入提示以下内容的正确方法是什么?
import random …Run Code Online (Sandbox Code Playgroud) 我有一个扩展基类的类。实例化后,我想检查子类是否具有从其基础实现的类之一,但我不确定最好的方法。 hasattr(self, '[method]')如果孩子没有实现,则返回 super 的方法,所以我试图区分两者。
这是一个例子:
class Base :
def __init__ ( self,) :
pass
def fail (self,) :
pass
# Now create the subclass w/o .fail
class Task ( Base ) :
def __init__ ( self, ):
print( hasattr( self, 'fail' ) ) # < returns True
Run Code Online (Sandbox Code Playgroud)
当Task()实例化时,它会打印, True因为Task继承.fail自Base. 但在这种情况下,我想知道Task Does Not Implement .fail,所以我想要False以某种方式返回。看来我正在寻找类似的东西isimplemented( self, 'fail' )。我缺少什么?
我正在尝试从父目录中的文件夹导入模型。我正在使用 sys.path.append()。我的项目结构:
-项目
在 file1.py 文件中:
sys.path.append('../Project')
from Project.folder2 import file2
Run Code Online (Sandbox Code Playgroud)
然后我得到:
ModuleNotFoundError: No module named Project
Run Code Online (Sandbox Code Playgroud)
我知道还有其他方法,但这似乎是最简单的。我不确定是否需要将绝对路径放入项目文件夹,但我希望不需要,因为我将在不同的计算机上运行该项目(差异绝对路径)。
我正在寻找一种工具,可以将函数中已添加的类型注释添加到 PyCharm 生成的文档字符串中。
我已经在 JetBrains 上关注这个问题很长时间了,但这个问题似乎还没有取得任何进展。
我也看到了这篇文章,但它似乎太具体了,只适用于谷歌文档字符串。
我已经在 PyPI 上查看了这个包,但这与我需要的相反。我需要的是将参数中提供的类型提示添加到文档字符串中,而不是相反。
这可能与如何使 PyCharm 从函数定义中获取类型提示并在文档字符串中填充类型值有关?,但我只需要一个通用的解决方案,或者至少一个可以与 Numpy docstring 或 reStructuredText 配合使用并且可以与 PyCharm 很好地配合的解决方案。
我只是看到自己回来研究这个东西,希望能得到一些东西,但找不到我需要的东西。什么工具可以用于此目的?
我对类型提示和文档字符串的使用感到困惑。它们不是重复的信息吗?
例如:
def my_func(name: str):
"""
print a name.
Parameters
----------
name : str
a given name
"""
print(name)
Run Code Online (Sandbox Code Playgroud)
信息不是name: str给出了两次吗?
我试图了解在键入函数时如何使用重载装饰器。如果我编写以下代码并通过 mypy 运行它:
from typing import Union, overload
@overload
def myfunc(a: float, b: float) -> float: ...
@overload
def myfunc(a: int, b: int) -> int: ...
def myfunc(a: Union[float, int], b: Union[float, int]) -> Union[float, int]:
return a + b
Run Code Online (Sandbox Code Playgroud)
然后我收到“错误:重载函数签名 2 永远不会匹配:签名 1 的参数类型相同或更广泛在 1 个文件中发现 1 个错误(已检查 1 个源文件)”
我不明白为什么签名 1(即浮点数)的参数类型比签名 2(即整数)更广泛。
这里发生了什么?
我正在尝试匹配类型注释,例如int | str,并使用正则表达式替换将它们替换为 string Union[int, str]。
期望的替换(之前和之后):
str|int|bool->Union[str,int,bool]Optional[int|tuple[str|int]]->Optional[Union[int,tuple[Union[str,int]]]]dict[str | int, list[B | C | Optional[D]]]->dict[Union[str,int], list[Union[B,C,Optional[D]]]]到目前为止我想出的正则表达式如下:
r"\w*(?:\[|,|^)[\t ]*((?'type'[a-zA-Z0-9_.\[\]]+)(?:[\t ]*\|[\t ]*(?&type))+)(?:\]|,|$)"
Run Code Online (Sandbox Code Playgroud)
您可以在 Regex Demo 上尝试一下。它并没有真正按照我想要的方式工作。到目前为止我注意到的问题:
到目前为止,它似乎无法处理嵌套的 Union 条件。例如,int | tuple[str|int] | bool似乎会导致一场匹配,而不是两次匹配(包括内部 Union 条件)。
正则表达式似乎]最后消耗了不必要的东西。
可能是最重要的一个,但我注意到 Python 中的模块似乎不支持正则表达式子例程re。这是我想到使用它的地方。
这主要是为了支持Python 3.7+ 的PEP 604语法,该语法需要前向声明(例如声明为字符串)注释才能支持,否则内置类型不支持该|运算符。
这是我想出的示例代码:
r"\w*(?:\[|,|^)[\t ]*((?'type'[a-zA-Z0-9_.\[\]]+)(?:[\t ]*\|[\t ]*(?&type))+)(?:\]|,|$)"
Run Code Online (Sandbox Code Playgroud)
对于 3.10 之前的 Python 版本,我使用__future__import 来避免出现以下错误: …
通常在Python中,可以使用以下技术来检测子类中的方法是否已被重写:
>>> class Foo:
... def mymethod(self): pass
...
>>> class Bar(Foo): pass
...
>>> Bar.mymethod is Foo.mymethod
True
Run Code Online (Sandbox Code Playgroud)
如果来自的方法尚未在 中被重写,则该表达式Bar.mymethod is Foo.mymethod将计算为,但如果该方法已在 中被重写,则该表达式将计算为。此技术适用于从 继承的 dunder 方法以及非 dunder 方法:TrueFooBarFalseBarobject
>>> Bar.__new__ is Foo.__new__
True
>>> Bar.__eq__ is Foo.__eq__
True
Run Code Online (Sandbox Code Playgroud)
我们可以在函数中形式化这个逻辑,如下所示:
def method_has_been_overridden(superclass, subclass, method_name):
"""
Return `True` if the method with the name `method_name`
has been overridden in the subclass
or an intermediate class in the method resolution …Run Code Online (Sandbox Code Playgroud) python ×9
type-hinting ×5
python-3.x ×3
docstring ×2
inheritance ×2
oop ×2
annotations ×1
covariance ×1
keyof ×1
mypy ×1
pandas ×1
pycharm ×1
regex ×1
superclass ×1