Skip to content

Commit

Permalink
example #166 update example to use base class AND metaclass
Browse files Browse the repository at this point in the history
  • Loading branch information
prjemian committed Jul 12, 2019
1 parent 4441a63 commit aa8085e
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 10 deletions.
10 changes: 5 additions & 5 deletions tests/trial/bacon.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@
* https://www.pythoncentral.io/how-metaclasses-work-technically-in-python-2-and-3/
"""

from plugin_base import Plugin
from plugin_base import AutoRegister, Parent

class File(metaclass=Plugin):
class File(Parent, metaclass=AutoRegister):
key = "#F"

class Date(metaclass=Plugin):
class Date(Parent, metaclass=AutoRegister):
key = "#D"

class Epoch(metaclass=Plugin):
class Epoch(Parent, metaclass=AutoRegister):
key = "#E"

class Comment(metaclass=Plugin):
class Comment(Parent, metaclass=AutoRegister):
key = "#C"
5 changes: 3 additions & 2 deletions tests/trial/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

# loop over registered plugins
for key, cls in plugins.get_registry().items():
if cls is not plugins.plugin_base.Plugin:
logger.info(f"key={key} class={cls}")
if cls is not plugins.plugin_base.AutoRegister:
obj = cls()
logger.info(f"key={key} class={cls} obj={obj}")

logger.info("-"*40)
10 changes: 9 additions & 1 deletion tests/trial/plugin_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def register_plugin(cls):
registry[key] = cls


class Plugin(type):
class AutoRegister(type):
__key__ = None
def __init__(cls, name, bases, dict):
logger.debug(" "*4 + "."*10)
Expand All @@ -60,3 +60,11 @@ def __new__(metaname, classname, baseclasses, attrs):
logger.debug(f'__new__: baseclasses={baseclasses}')
logger.debug(f'__new__: attrs={attrs}')
return type.__new__(metaname, classname, baseclasses, attrs)


class Parent:
key = None
def __str__(self):
return(f"{self.__class__.__name__}(key='{self.key}')")
def do_this(self):
print(self.__class__.__name__)
4 changes: 2 additions & 2 deletions tests/trial/spam.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* https://www.pythoncentral.io/how-metaclasses-work-technically-in-python-2-and-3/
"""

from plugin_base import Plugin
from plugin_base import AutoRegister, Parent

class Scan(metaclass=Plugin):
class Scan(Parent, metaclass=AutoRegister):
key = "#S"

0 comments on commit aa8085e

Please sign in to comment.