Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decoratros, class
#1
Hi, I've got code like that:
def check_str_or_int(fun):
    def inside_check(arg, obj, *tags):
        if type(arg)==int:
            fun(arg, obj, *tags)
        elif type(arg)==str:
            fun(obj.get_num_by_name(arg), obj,*tags)
    return inside_check
class PrzestrzenObiektow():
...
    @check_str_or_int
    def add_tags(self, arg1, arg2, *tags):
        pass
from Krzykacz import przestrzen_obiektow


def setup_module():
    przestrzen = przestrzen_obiektow.PrzestrzenObiektow()
    przestrzen.dodawanie_do_przestrzeni(None, 'a',
                                        magnet_points={'konce': [(10, 10), (300, 700)], 'srodki': [(110, 1000)]})
    przestrzen.dodawanie_do_przestrzeni(None, 'b', magnet_points={'konce': [(200, 10), (89, 90), (90, 89)],
                                                                   'srodki': [(110, 110)]})

    przestrzen.add_tags()


setup_module()
When I call przestrzen.add_tags(), I expect:
Error:
TypeError: inside_check() missing 2 required positional arguments: 'arg' and 'obj'
instead I get:
Error:
TypeError: inside_check() missing 1 required positional argument: 'obj'
in debugger 'arg' is <Krzykacz.przestrzen_obiektow.PrzestrzenObiektow object at 0x00000197241BCB08> , witch is PrzestrzenObiektow instance. It looks like 'self' is pass to the decorator. How to fix it? I want to use these decorator with method and funtion. Could you pls help?
Reply
#2
The inner function has to have the same arguments as the function it decorates. Normally this is done by using *args and **kwargs which match any arguments, but in your case your inside_check function needs a "self" argument. It doesn't have to use it, but it needs it so it can provide that as an argument and make the signature match.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020