Skip to content

Commit

Permalink
Updated abstract.py example.
Browse files Browse the repository at this point in the history
  • Loading branch information
brandjon committed Dec 21, 2014
1 parent bb223c6 commit 7755c05
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions examples/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@
from abc import ABCMeta, abstractmethod
from simplestruct import Struct, Field, MetaStruct


# A simple ABC. Subclasses must provide an override for foo().
class Abstract(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass

# If we ran this code
#
# class Concrete(Abstract, Struct):
# f = Field
# def foo(self):
# return self.f ** 2
#
# we would get the following error:
#
# TypeError: metaclass conflict: the metaclass of a derived class
# must be a (non-strict) subclass of the metaclasses of all its bases
#
# So let's make a trivial subclass of ABCMeta and MetaStruct.
# ABCs rely on a metaclass that conflicts with Struct's metaclass.
try:
class Concrete(Abstract, Struct):
f = Field
def foo(self):
return self.f ** 2

except TypeError as e:
print(e)
# metaclass conflict: the metaclass of a derived class must
# be a (non-strict) subclass of the metaclasses of all its bases

# So let's make a trivial subclass of ABCMeta and MetaStruct.
class ABCMetaStruct(MetaStruct, ABCMeta):
pass

Expand All @@ -33,13 +34,13 @@ def foo(self):
c = Concrete(5)
print(c.foo()) # 25

# For convenience we can also do

# For convenience we can make a version of Struct that
# incorporates the common metaclass.
class ABCStruct(Struct, metaclass=ABCMetaStruct):
pass

# and then

# Now we only have to do:
class Concrete(Abstract, ABCStruct):
f = Field
def foo(self):
Expand Down

0 comments on commit 7755c05

Please sign in to comment.