Browse Source

[commands] Allow converters to be instantiated.

This allows for you to create converters that can have varying
behaviour using the converter's __init__ instead of having to do a
meta-class based approach to get around the fact that __init__ is part
of the interface.

To make up for the lack of __init__, a new method Converter.prepare was
added to do the work that __init__ used to do.
pull/1278/head
Rapptz 8 years ago
parent
commit
e10cae5dbc
  1. 8
      discord/ext/commands/converter.py
  2. 14
      discord/ext/commands/core.py

8
discord/ext/commands/converter.py

@ -54,6 +54,9 @@ class Converter:
to do its conversion logic. This method could be a coroutine or a regular to do its conversion logic. This method could be a coroutine or a regular
function. function.
Before the convert method is called, :meth:`prepare` is called. This
method must set the attributes below if overwritten.
Attributes Attributes
----------- -----------
ctx: :class:`Context` ctx: :class:`Context`
@ -61,7 +64,7 @@ class Converter:
argument: str argument: str
The argument that is being converted. The argument that is being converted.
""" """
def __init__(self, ctx, argument): def prepare(self, ctx, argument):
self.ctx = ctx self.ctx = ctx
self.argument = argument self.argument = argument
@ -69,8 +72,7 @@ class Converter:
raise NotImplementedError('Derived classes need to implement this.') raise NotImplementedError('Derived classes need to implement this.')
class IDConverter(Converter): class IDConverter(Converter):
def __init__(self, ctx, argument): def __init__(self):
super().__init__(ctx, argument)
self._id_regex = re.compile(r'([0-9]{15,21})$') self._id_regex = re.compile(r'([0-9]{15,21})$')
def _get_id_match(self): def _get_id_match(self):

14
discord/ext/commands/core.py

@ -203,11 +203,15 @@ class Command:
converter = getattr(converters, converter.__name__ + 'Converter') converter = getattr(converters, converter.__name__ + 'Converter')
if inspect.isclass(converter) and issubclass(converter, converters.Converter): if inspect.isclass(converter) and issubclass(converter, converters.Converter):
instance = converter(ctx, argument) instance = converter()
if asyncio.iscoroutinefunction(instance.convert): instance.prepare(ctx, argument)
return (yield from instance.convert()) ret = yield from discord.utils.maybe_coroutine(instance.convert)
else: return ret
return instance.convert()
if isinstance(converter, converters.Converter):
converter.prepare(ctx, argument)
ret = yield from discord.utils.maybe_coroutine(converter.convert)
return ret
return converter(argument) return converter(argument)

Loading…
Cancel
Save