1

I'm getting an error that has me pretty stumped.

#! /usr/bin/env python3
from sys       import modules
from inspect   import isclass
from functools import partial
from abc       import abstractmethod
from abc       import ABC as AbstractClass


class Decoration(AbstractClass):
    defaults = {}

    def __init__(self, *list, **map):
        self.list = list
        self.map = map

    def __get__(self, caller, owner):
        return partial(self.__call__, caller)

    @abstractmethod
    def __call__(self, decoratee, *list, **map):
        pass

    @staticmethod
    def set_defaults(defaults):
        Decoration.defaults = defaults


class Decorator(Decoration):

    def __init__(self, *list, **map):
        super().__init__(self, *list, **map)

    def __call__(self, function, *list, **map):
        print(function)
        def decorated(*list, **map):
            if map:
                for decorator in map:
                    for arguments in map[decorator]:
                        function = getattr([__name__], decorator)(function, arguments)
            return function(*list, **map)
        return decorated


@Decorator()
def dummy(*list, **map):
    for item in list:
        print(item)
    for k, v in map:
        print('{} {}'.format(k, v))


def main():
    dummy({'banana': True})


if __name__ == '__main__':
    main()

On the "function = getattr ..." line, I'm getting this error:

UnboundLocalError: local variable 'function' referenced before assignment

I'm confused mainly because the print statement above finds the function's definition as

<function dummy at (address)>

which is correct. Furthermore, deleting that line lets the program run fine and return currently on the next line. As far as I can tell, it's not a syntax problem of getattr. Any ideas?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Anthony
  • 1,015
  • 8
  • 22
  • You are assigning the variable `function` and using it all in the same line. What exactly are you trying to do there? You also have a parameter named `function` in the outer scope. I think you need to use different variable names. – Code-Apprentice Jun 02 '18 at 22:39
  • @Aran-Fey That's exactly it! Thank you – Anthony Jun 02 '18 at 22:44
  • 1
    @Code-Apprentice I was trying to manipulate the argument "function" in a way akin to "x = f(x)", but now Isee I needed to add "nonlocal function" – Anthony Jun 02 '18 at 22:45

0 Answers0