Question

I am trying to do the following, but am getting an exception NameError("global name 'rid' is not defined",

def safe_forcecall(fn):
    def _safe_forcecall(self, *args, **kwargs):
        if self._token_valid(rid) is not None:
            return fn(self, *args, **kwargs)
    return _safe_forcecall


@safe_forcecall
def add_booking(self, rid, data):
    ...
Was it helpful?

Solution

You are passing in rid as a positional argument, so can be found in args instead:

if self._token_valid(args[0]) is not None:

If your decorator always needs access to that argument, just name it explicitly:

def safe_forcecall(fn):
    def _safe_forcecall(self, rid, *args, **kwargs):
        if self._token_valid(rid) is not None:
            return fn(self, rid, *args, **kwargs)
    return _safe_forcecall

You won't find the value in the kwargs dictionary; only if you were to call add_booking with a rid=rid argument would it be placed there. By using an explicit rid argument in your decorator wrapper function, you make sure it is always bound to the rid name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top