我最近發現了dataclasses Python 包。在我的型別注釋中使用自定義類時遇到問題。我在下面有一個簡單的例子。
當Entry類被傳遞location引數時,該引數的值應該被用來構造一個Location物件。同樣,當Entry類被傳遞一個字串作為creationDate引數時,它應該被決議(使用dateutil.parser.parse)來創建一個datetime.datetime物件。在我的代碼中,locationandcreationDate引數不會轉換為Locationanddatetime.datetime物件。我不知道如何使這項作業。請指教。
當然,我可以在不使用 dataclasses 包的情況下做到這一點。它將添加更多樣板代碼。我也以此為借口來學習 dataclasses 包,這樣我下次可以更有效地使用它。
試試看
import datetime
import dateutil.parser
import dataclasses
import inspect
@dataclasses.dataclass
class Location():
latitude: float
longitude: float
@dataclasses.dataclass
class Entry():
"""
A single DayOne entry
"""
creationDate: datetime.datetime = \
dataclasses.field(default_factory=dateutil.parser.parse)
location: Location = None
@classmethod
def factory(cls, **kwargs):
class_fields = {k:v for k,v in kwargs.items()
if k in inspect.signature(cls).parameters}
return cls(**class_fields)
if __name__ == "__main__":
print("Converting from dayone to jekyll\n")
args = {
"creationDate": '2022-05-30T04:44:33Z',
"location": {
'latitude': -37.8721,
'longitude': 175.6829,
'named': 'Hobbiton'
},
"text": "In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, and that means comfort."
}
entry = Entry.factory(**args)
print(type(entry.location))
print(type(entry.creationDate))
uj5u.com熱心網友回復:
一種選擇是使用dataclass-wizard,它比pydantic. 它對早期的 python 版本使用typing-extensions模塊,但在 3.10 中它只依賴于核心 python stdlib。
用法:
from __future__ import annotations # can be removed in 3.10
import datetime
# import dateutil.parser
import dataclasses
from pprint import pprint
from dataclass_wizard import JSONWizard
@dataclasses.dataclass
class Location:
latitude: float
longitude: float
named: str | None = None
@dataclasses.dataclass
class Entry(JSONWizard):
"""
A single DayOne entry
"""
creation_date: datetime.datetime
location: Location | None = None
if __name__ == "__main__":
print("Converting from dayone to jekyll\n")
args = {
"creationDate": '2022-05-30T04:44:33Z',
"location": {
'latitude': -37.8721,
'longitude': 175.6829,
'named': 'Hobbiton'
},
"text": "In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, and that means comfort."
}
entry = Entry.from_dict(args)
print(type(entry.location))
print(type(entry.creation_date))
print()
print('Object:')
pprint(entry)
結果:
Converting from dayone to jekyll
<class '__main__.Location'>
<class 'datetime.datetime'>
Object:
Entry(creation_date=datetime.datetime(2022, 5, 30, 4, 44, 33, tzinfo=datetime.timezone.utc),
location=Location(latitude=-37.8721, longitude=175.6829, named='Hobbiton'))
旁注:我實際上并沒有想過用它dateutil.parser.parse來決議日期字串,盡管這可能是一個好主意。當前的實作使用datetime.fromisoformat在一般用例中運行良好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487495.html
下一篇:將Axios配置為可重用模塊
