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

Stavros Macrakis macrakis at alum.mit.edu
Sun Jul 26 14:52:26 EDT 2020


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)).


More information about the Python-list mailing list