meteclasses 2.x/3.x compatibility

J

James Mills

Hi all,

Is there a compatible way to use meteclasses
in both Python 2.x (2.6 to 2.7) and Python 3.x
(3.0 to 3.2).

Python 2.x:

class Foo(object):

__meteclass__ = MyMetaClass

Python 3.x:

class Foo(metaclass=MyMetaClass):
pass

Thanks,

cheers
James
 
S

Steven D'Aprano

Hi all,

Is there a compatible way to use meteclasses in both Python 2.x (2.6 to
2.7) and Python 3.x (3.0 to 3.2).


Untested:

if sys.version >= "3":
kw = {'metaclass': MyMetaClass}
else:
kw = {}

class Foo(object, **kw):
if sys.version < "3":
__metaclass__ = MyMetaClass


Inelegant as it gets, but it should work.
 
J

James Mills

What I do in Lepl is use two stages.  The first calls the type/metaclass directly and the second subclasses that.  This avoids using the "sugar" that changes between 2 and 3.

So, for example, in http://code.google.com/p/lepl/source/browse/src/lepl/matchers/matcher.py#40 I have

 _Matcher = ABCMeta('_Matcher', (object, ), {})

and then

 class Matcher(_Matcher):
     ...

Thank Andrew. I like this approach Elegance wins for me :)

cheers
James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top