[Python-Dev] Return type of alternative constructors

Ethan Furman ethan at stoneleaf.us
Sat May 7 19:14:12 EDT 2016


On 05/07/2016 03:39 PM, Serhiy Storchaka wrote:
> Some types have alternative constructors -- class methods used to create
> an instance of the class. For example: int.from_bytes(),
> float.fromhex(), dict.fromkeys(), Decimal.from_float().
>
> But what should return these methods for subclasses? Should they return
> an instance of base class or an instance of subclass? Almost all
> alternative constructors return an instance of subclass (exceptions are
> new in 3.6 bytes.fromhex() and bytearray.fromhex() that return bare
> bytes and bytearray). But there is a problem, because this allows to
> break invariants provided by the main constructor.

Please ignore my comments in that issue.  I actually prefer that class 
constructors go through the subclass' __new__ and __init__.  Overriding 
parent class methods for the sole purpose of getting the subclass's type 
is quite irritating.

--
~Ethan~


More information about the Python-Dev mailing list