いつものやつです。対応していない値をjson.dumps()に与えるとTypeErrorが発生するやつです。 TypeError 例えばこういうdataclassを定義して。 from dataclasses import dataclass, asdict @dataclass class Point: x: int y: int json.dumpsするとTypeError import json p = Point(x=1, y=2) # TypeError: Object of type Point is not JSON serializable print(json.dumps(p)) default いつもどおりにdefaultを渡してあげる必要があります。ちょっとめんどくさいですが、is_dataclassという関数で調べられるのでどうにかなります。 import json
jsonのencodeエラーについては昔に書いたこの辺を見てもらうとして。 pythonでjson出力する際で対応していない型(e.g. datetime)の値を変換しながら出力したい - Qiita 今回の主題は、json.dumpsに渡すdefaultの関数としてfunctools.singledispatchが有用かもという話。 使いかた singledispatchを利用したモジュールを定義 例えば以下のようなextjsonモジュールを定義してあげる。 extjson.py import json from functools import ( singledispatch, partial, ) @singledispatch def encode(o): raise TypeError("Object of type '%s' is not JSON serializable"
今日は Single-dispatch generic functions (PEP-443)。Generic functionは汎用関数と訳されることも多いが、言語によって微妙に違う使われ方をしている。Pythonでは「引数の型によって動作が異なる複数の関数に同じ名前をつける」という意味合いで使われているようだ。 と書いてもさっぱりわからないので、例示。引数の型によって出力が異なる関数を考える。Generic functionsを使わないとこんな感じ。 def print_func(arg): arg_type = type(arg) if arg_type is int: print("found integer:", arg) elif arg_type is list: print("found list:", arg) else: print("found something:"
mypyのdmypyの実装の仕方を把握する。知りたいことは裏側でのprocessの管理の仕方とクライアントとサーバー間のデータのやり取りの仕方。 準備 $ git clone --depth 1 git@github.com:python/mypy エントリーポイントの把握 インストールされるコマンドの確認(setup.py) setup(name='mypy', ... entry_points={'console_scripts': ['mypy=mypy.__main__:console_entry', 'stubgen=mypy.stubgen:main', 'dmypy=mypy.dmypy:main', ]}, data_files=data_files, ... mypy.dmypy:main()がエントリーポイント実際のファイル。 main.py ほとんどargparseを
地道な方法 地道に下の通り書くと型チェックを通りました。 def remove_none_iterator(it: Iterator[Optional[int]]) -> Iterator[int]: while True: try: elem = next(it) while elem is None: elem = next(it) yield elem except StopIteration: return def remove_none(iterable: Iterable[Optional[int]]) -> Iterable[int]: it = iter(iterable) return remove_none_iterator(it) ただしこれだと返り値が必ずイテレーターになってしまいます。しかしそもそも filter() 関数は iterable を受け取ってイテレー
ちょっとだけ背景説明 なんでそんなことがしたくなったかというと、やっぱり定義を記述したらおしまいでいられる世界が理想なので。そして特定の領域(e.g. OpenAPI, GraphQL, Protcol Buffers, database定義, ...)に属さないような中立的な表現が欲しくなったので。 この記事は一言で言うならpythonのクラスの各フィールドにどうやってメタデータを持たせようか?ということに対するメモです。 どうしてpython? 現状よく触るのがgoとpythonなのですが、goは直和型が素直に記述できないので1。 普及している言語の中ではTypeScriptの方がゆるふわな表現を良い感じに型パズルしやすいとは想うのですが、literal typeやtyped dictやprotocolなどそこそこpythonでも悪くはない形で型チェックが可能になってきたかなーというこ
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work. Try for free Learn more
PEP 484 – Type Hints PEP 484 – Type Hints Author: Guido van Rossum <guido at python.org>, Jukka Lehtosalo <jukka.lehtosalo at iki.fi>, Łukasz Langa <lukasz at python.org> BDFL-Delegate: Mark Shannon Discussions-To: Python-Dev list Status: Final Type: Standards Track Topic: Typing Created: 29-Sep-2014 Python-Version: 3.5 Post-History: 16-Jan-2015, 20-Mar-2015, 17-Apr-2015, 20-May-2015, 22-May-2015
Andrew Montalenti @amontalenti – Founder/CTO. Coding in: Python, JavaScript, Zig. Menu and widgets In 2010, the Python core team wrote PEP 3107, which introduced function annotations for Python 3.x. Nearly 4 years ago, I wrote this response to the PEP, but I published it to a discussion site that ended up becoming defunct (Clusterify). I saw that recently, interest in function annotations for type
デフォルト引数周りの型のことでちょっと把握できなかった部分があったのでメモ。 余分なデフォルト引数を持つ実装について 例えば、以下の様なプロトコルがあるとする。 import typing as t import typing_extensions as tx class Adder(tx.Protocol): def add(self, x: int, y: int) -> int: ... このAdder.addメソッドはデフォルト引数を持たない。一方で、デフォルト引数を持つような実装はこのプロトコルの制約を満たすのかということが気になる。 例えば以下のようなもの class A: def add(self, x: int, y: int, *, verbose: bool = False) -> int: return x + y class B: def add(self, x:
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く