What for -- for? (was A bug?)

Zachary Ware zachary.ware+pylist at gmail.com
Wed Oct 29 05:59:13 CET 2014


On Tue, Oct 28, 2014 at 11:40 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> On Wednesday, October 29, 2014 9:53:46 AM UTC+5:30, Zachary Ware wrote:
>> On Tue, Oct 28, 2014 at 11:16 PM, Zachary Ware wrote:
>> > def get_abc_map(cls):
>> >    return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if
>> > n[0].isupper()}
>>
>> Of course, Gmail decided to wrap my long line for me.  In case it's
>> not obvious, that should be a single line.
>
> Thanks
>
> Wrapping -- no problem.
> But the isupper looks like black-magic :-)
>
> And removing the ' ... if n[0].isupper()'
> breaks the code

It's a terrible hack for 2/3 compatibility; in 3 I'd do "if not
n.startswith('__')" since the Python 3 collections.abc module only
contains ABCs (and the standard dunder names).  Python 2 has all the
ABCs mixed into the toplevel collections namespace with some other
non-ABCs, but it happens that all the ABCs are capitalized, while the
non-ABCs are not.  The ABCs are imported into collections from
_abcoll, but _abcoll also some uncapitalized non-ABCs as well.

For somewhat greyer magic, do 'from abc import ABCMeta' and filter the
collections<.abc> namespace with isinstance(obj, ABCMeta).  I just
used the above because it's short and sweet and keeps the name handy
:)

-- 
Zach



More information about the Python-list mailing list