Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

When I:

Use a classmethod as a decorator wrapper

Have a conditional statement inside the decorator

Put a variable assignment inside the decorator

python raises an UnboundLocalError exception.

However, when I remove the variable assignment and replace it with a print function everything works fine (it does print). Which indicate that the variable is indeed defined.

Snippet 1

class TestClass:

    @classmethod

    def include(cls, name=None):

        def dec(func):

            if name is None:

                name=1

            return func

        return dec

@TestClass.include()

def test(): pass

Snippet 2

class TestClass:

    @classmethod

    def include(cls, name=None):

        def dec(func):

            if name is None:

                print(name)

            return func

        return dec

@TestClass.include()

def test(): pass

In snippet 1 nothing should happen but it raised the following exception:

Traceback (most recent call last):

  File "main.py", line 9, in <module>

    @TestClass.include()

  File "main.py", line 5, in dec

    if name is None:

UnboundLocalError: local variable 'name' referenced before assignment

Snippet 2 prints None as it should.

Am I doing something wrong? or is this a problem in python's implementation?

1 Answer

0 votes
by (25.1k points)

You are trying to assign to the nonlocal variable name from inside the function dec.

Whenever you assign to a variable inside a function in Python that variable is automatically local to the function unless you explicitly tell Python that it should be treated as nonlocal or global

Just add a nonlocal declaration and it will do what you expected:

class TestClass:

    @classmethod

    def include(cls, name=None):

        def dec(func):

            nonlocal name 

            if name is None:

                name=1

            return func

        return dec

@TestClass.include()

def test(): pass

Related questions

0 votes
1 answer
asked Jul 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Feb 20, 2021 in Java by rahulnayar01123 (6.1k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...