我有一个带有可变字段(列表)的数据类。我希望实现的是,即使在 __init__ 调用中显式设置为 None ,该字段也永远不会为 None 。在普通的类中,实现起来很简单:
class A:
def __init__(self, l: Optional[List[int]] = None):
if l is None:
l = []
self.l = l
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以仅使用dataclasses.field函数来实现相同的结果,即无需显式实现 __init__ 方法(当类有很多属性时,这会很麻烦)?default_factory当提供的 init 参数为 None 时,我可以强制 dataclasses.field 调用它吗?
我有一个问题,我需要在哈希映射中进行模糊查找,即返回与最接近查询的键对应的值,在我的例子中是由 Levenshtein 距离测量的。
我目前的方法是dict使用特殊的查找方法进行子类化,该方法计算所有键的 Levenshtein 距离,然后返回分数最低的键的值。基本上是这样的:
import Levenshtein
class FuzzyLookupDict(dict):
def fuzzy_lookup(self, query):
levs = [(key, Levenshtein.ratio(query, key)) for key in self.keys()]
key, score = max(levs, key=lambda lev: lev[1])
return self.get(key)
Run Code Online (Sandbox Code Playgroud)
这是一个很好的方法还是有我没有想到的更好的解决方案?
比较这两个函数:
from typing import Optional
def foo1(bar: str = None) -> None:
print(bar)
def foo2(bar: Optional[str] = None) -> None:
print(bar)
Run Code Online (Sandbox Code Playgroud)
Mypy 不会抱怨他们中的任何一个。那么Optional[]真的有必要吗?这两个声明之间有什么细微的区别吗?
我正在尝试将Django(v2.1)应用程序部署到App Engines Python37运行时。这是我的app.yaml内容,取自Google的示例:
# [START django_app]
runtime: python37
#api_version: 1
#threadsafe: yes
handlers:
- url: /static
static_dir: static/
- url: .*
script: <project_name>.wsgi.application
# Only pure Python libraries can be vendored
# Python libraries that use C extensions can
# only be included if they are part of the App Engine SDK
# Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27
#libraries:
#- name: MySQLdb
# version: 1.2.5
# [END django_app]
# Google App Engine limits application deployments to …Run Code Online (Sandbox Code Playgroud) google-app-engine google-cloud-platform gcloud google-app-engine-python
我正在使用基于 aiohttp 的第三方 API 客户端库。该库没有将其客户端实现为上下文管理器,但只要我始终aiohttp.ClientSession手动关闭(对吗?),这应该没有问题。
问题是,即使在仔细执行此操作之后,我仍然收到警告,Unclosed client session但没有任何信息来自它的来源。我正在使用 捕获警告回溯pytest -W error::ResourceWarning,但结果很简单
.Exception ignored in: <bound method ClientSession.__del__ of <aiohttp.client.ClientSession object at 0x10fc15ba8>>
Traceback (most recent call last):
File "<PROJECT>/venv/lib/python3.6/site-packages/aiohttp/client.py", line 211, in __del__
**kwargs)
ResourceWarning: Unclosed client session <aiohttp.client.ClientSession object at 0x10fc15ba8>
Run Code Online (Sandbox Code Playgroud)
即单帧的回溯。
有人可以告诉我我在这里做错了什么以及如何获得有关该警告的更多信息吗?
python ×3
aiohttp ×1
gcloud ×1
hashmap ×1
hashtable ×1
mypy ×1
type-hinting ×1
typechecking ×1