python PEP suggestion

Terry Reedy tjreedy at udel.edu
Sun Nov 8 17:26:36 EST 2015


On 11/6/2015 1:21 PM, Dan Strohl wrote:
> All,
>
> I wanted to run the following thought past the list as a possible PEP enhancement suggestion to see if it feels like something that is worth proposing.   I know it is not in the PEP format at this point, I can, and will, clean it up if needed, I am just trying to throw it against the wall at this point to see if it resonates... (or if it falls flat and goes "splat" <grin>).
>
> Thoughts?

At first glance, plausible, but I am not sure needed, and it seems a bit 
contrary to how Python currently works.

> New special method name to allow for more flexible object type casting/access, and extend type() to cast objects using this special method name.
>
> Overview:
>
> Have a new special method name that would allow a given objects to request information from another object in a given type, or to cast an object into a different type, and extend the built in type() function to use this.
>
> Rationale:
> There is currently __str__, __int__, and __bool__ that allow me to tell an object how it should reply to a request for these types of basic data types.  However if I want to access a copy of the objet in dict form, or as a list, or if I am trying to convert something using json, there is no standard way of doing that for a custom object (I know I can do __getitem__ and/or __iter__, but I many processes don't try these if the object is not a subclass of dict or list/tuple)

Conditional execution, indexing (__index__), numeric conversions 
(__float__ also), and displaying are special cases related to syntax 
operations.  Functions that unnecessarily restrict inputs to subclasses 
of list or dict will not be solved by this.  You have left out the use 
of abstract base classes.  An iterable that can be used as a mapping can 
register itself as a mapping.  Json could check whether something is a 
sequence or mapping and iterate to get values or pairs of values.  Of 
course, the tranformation would be unidirectional.

> Proposal:
> What I am proposing is something like:
>
> object.__cast__(self, to_class):
>                                """
>                                to_class: the class type that you wish to return.
>                                """

The excessive indents of 31 and 15 spaces make the rest of this post 
unnecessarily hard to read.

-- 
Terry Jan Reedy




More information about the Python-list mailing list