パフォーマンス指向の typemylib.color.Hardware
と、それに対応するユーザーフレンドリーなと があるmylib.color.RGB
としmylib.color.HSB
ます。ユーザーフレンドリーな色がライブラリ関数に渡されると、 に変換されcolor.Hardware
ます。現在は、渡された引数の型を調べることで実装されています。しかし、将来的には、対応する変換機能を提供する任意のタイプから受け入れて自動変換したいと考えています。たとえば、「otherlib.color.LAB」を実装するサードパーティ ライブラリ。
現在、私は次のようなプロトタイプで遊んでいます。
class somelib:
class A(object):
def __init__(self, value):
assert isinstance(value, int)
self._value = value
def get(self):
return self._value
class userlib:
class B(object):
def __init__(self, value):
self._value = value
def __toA(self):
try: value = int(self._value)
except: value = 0
return somelib.A(value)
__typecasts__ = {somelib.A: __toA}
def autocast(obj, cast_type):
if isinstance(obj, cast_type): return obj
try: casts = getattr(obj, '__typecasts__')
except AttributeError: raise TypeError, 'type cast protocol not implemented at all in', obj
try: fn = casts[cast_type]
except KeyError: raise TypeError, 'type cast to {0} not implemented in {1}'.format(cast_type, obj)
return fn(obj)
def printValueOfA(a):
a = autocast(a, somelib.A)
print 'value of a is', a.get()
printValueOfA(userlib.B(42.42)) # value of a is 42
printValueOfA(userlib.B('derp')) # value of a is 0
そして、これが私の 2 番目のプロトタイプです。邪魔にはなりませんが、より冗長です。
# typecast.py
_casts = dict()
def registerTypeCast(from_type, to_type, cast_fn = None):
if cast_fn is None:
cast_fn = to_type
key = (from_type, to_type)
global _casts
_casts[key] = cast_fn
def typeCast(obj, to_type):
if isinstance(obj, to_type): return obj
from_type = type(obj)
key = (from_type, to_type)
fn = _casts.get(key)
if (fn is None) or (fn is NotImplemented):
raise TypeError, "type cast from {0} to {1} not provided".format(from_type, to_type)
return fn(obj)
# test.py
from typecast import *
registerTypeCast(int, str)
v = typeCast(42, str)
print "result:", type(v), repr(v)
質問。同じ機能を持つライブラリは存在しますか? (私は車輪を再発明したくありませんが、私の google-fu は None を生成します。) または、より良い (おそらくより Pythonic な) アプローチを提案できますか?
編集: 2 番目のプロトタイプを追加しました。