git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to cast to a type WAS: How to limit *length* of PrettyPrinter


I was a bit unhappy with my convert function:

        def convert(typ,obj):
             newobj = typ.__new__(typ,obj)
             newobj.__init__(obj)
             return newobj

because it called __xxx__ functions, which are supposed to be internal. It
was also a surprise that __new__ ignores the obj for (mutable) lists, but
__init__ ignores the obj for (immutable) tuples (rather than throwing an
exception).

Reading the reference manual, I see that I was right to be unhappy, because
the straightforward way is:

        def convert(typ,obj): return typ(obj)

and it works in other cases as well, e.g., type(3.4)(True) and
type({})((i,i) for i in range(0,2)).