Scope of decorator argument

Discussion in 'Python' started by Gregor Horvath, Oct 17, 2006.

  1. Hi,

    this:

    class base(object):
    @adecorator(xy)
    def edit(self):
    print "edit"

    class child(base):
    xy = 3


    obviously fails because "xy" is not bound at class creation time of the
    base object.

    One solution could be delegation:

    class base(object):
    @classmethod
    def edit(self):
    print "do the real work here"

    class child(object):
    xy = 3
    mybase = base

    @adecorator(xy)
    def edit(self, *args, **kwargs):
    self.mybase.edit(*args, **kwargs)

    But then I have the ugly boiler plate delegation code in child.

    Is there any other solution, probably with metaclasses ?

    --
    Servus, Gregor
    Gregor Horvath, Oct 17, 2006
    #1
    1. Advertising

  2. Gregor Horvath schrieb:
    >
    > Is there any other solution, probably with metaclasses ?
    >


    I've found this one:

    class mymeta(type):
    def __new__(meta, class_name, bases, new_attrs):
    new_attrs["edit"] = adecorator(new_attrs['xy'])(bases[0].edit))
    return type.__new__(meta, class_name, bases, new_attrs)

    class base(object):
    def edit(self):
    print "%s edit" % self

    class child(base):
    __metaclass__ = mymeta
    xy = 3


    Don't know if it's the best solution but it seems to work.

    --
    Servus, Gregor
    Gregor Horvath, Oct 17, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    931
    Paul Opal
    Oct 11, 2004
  2. ann
    Replies:
    13
    Views:
    652
    Patricia Shanahan
    Sep 13, 2005
  3. Chris
    Replies:
    20
    Views:
    703
    Bruno Desthuilliers
    Dec 23, 2006
  4. glomde
    Replies:
    5
    Views:
    515
    glomde
    Mar 29, 2007
  5. mk
    Replies:
    0
    Views:
    268
Loading...

Share This Page