Subclassing tuple and introspection

Ian Kelly ian.g.kelly at gmail.com
Wed Dec 2 18:46:57 EST 2015


On Wed, Dec 2, 2015 at 4:32 PM, Joseph L. Casale
<jcasale at activenetwerx.com> wrote:
> I need to return a collection of various types, since python doesn't
> have the terse facility of extension methods like C#, subclassing tuple
> and adding a method seems like a terse way to accommodate this.

If you're not already familiar with collections.namedtuple, have a
look at it, as it sounds like just naming the fields may be all that
you need. You can also subclass it further to add methods if desired.

> However, if the method returns one element of the collection, how can
> one enable introspection for users of IDE's that the resulting reference
> is of type A, and therefor has A's fields?
>
> For example:
> col = (Class(..), Class(...))
> item = col[0]
>
> Introspection will now enumerate item as an instance of Class, providing
> its fields. The subclass of tuple breaks this.
>
> Is there a better way to do this?

I think that's going to depend heavily on the specific IDE being used,
but for general usage you might consider using PEP 484 type
annotations; I know that at least PyCharm supports their use for type
hinting.



More information about the Python-list mailing list