[New-bugs-announce] [issue11788] Decorator class with optional arguments and a __call__ method gets not called when there are no arguments

Carsten Klein report at bugs.python.org
Wed Apr 6 23:46:54 CEST 2011


New submission from Carsten Klein <carsten.klein at axn-software.de>:

Scenario:

class deco(object):
  def __init__(self, optional = False):
    self._optional = optional

  def __call__(self, decorated):
    decorated.optional = self._optional
    return decorated

@deco
class y(object):
  pass

will fail decorating the class since y is passed in as the first parameter to deco.__init__, and deco.__call__ will never be called.

@deco(optional = True)
class y(object):
  pass

will succeed.

I wonder why there is a distinction between decorator class w/ arguments and decorator class w/o arguments?

Guessing that one would like to have a decorator class decorating another class and also acting as a kind of proxy by implementing a __call__ method, this could also be achieved by further indirection, provided that it will not break existing code.

A working alternative would be a decorator function like this:

def deco(_decorated = None, optional = False):
  def _wrapped(decorated):
    decorated.optional = optional
    return decorated
  if _decorated is not None:
    return _wrapped(decorated)
  return _wrapped

Is there a chance that the behavior of the decorator class will be fixed in a future release?

Expected behavior for the decorator class would be:

if formal parameter list has optional parameters and actual parameter list is empty and there are no formal mandatory parameters:
   if decorator class is callable:
      deco = decorator class ()
      decor.__call__(decorated)
   else:
      fall back to old behaviour, requiring the decorator class __init__ method to have one mandatory parameter
else:
  deco = decorator class(actual parameters...)
  deco.__call__(decorated)

TIA

----------
components: Interpreter Core
messages: 133171
nosy: carsten.klein
priority: normal
severity: normal
status: open
title: Decorator class with optional arguments and a __call__ method gets not called when there are no arguments
type: behavior
versions: Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11788>
_______________________________________


More information about the New-bugs-announce mailing list