Search code examples
python-3.xkeyword-argument

Is there a way to solve 'local variable 'kwargs' referenced before assignment' from __init__?


I have a Class that takes in **kwargs. I want to be able to use it within a function inside the class. I've looked at other solutions that say one must use return self.kwargs, but I'm not sure where I must do it (outside of the function, or inside the function but at the end)

class Foo():
    def __init__(self, name:str, **kwargs):
        self.name = name
        self.kwargs = kwargs
        # print(kwargs/self.kwargs) returns the dictionary as I expected

    ## There's an __enter__ and __exit__ that does nothing, just returns self

    def show():
        if kwargs:
            print(name, f"{key} and {value}" for key, value in self.kwargs.items())    # Using kwargs.items() didn't work too

        else:
            print(name)

        return self.kwargs

Then I did:

with Foo('some_name', foo='bar', foo_bar='baz') as f:
    f.show()

The error I'm getting is:

  File "/...", line 73, in <module>
    f.show()
  File "/...", line 96, in show
    if kwargs:
UnboundLocalError: local variable 'kwargs' referenced before assignment

What am I doing wrong here?

Thanks.


Solution

  • A few things are wrong. First the function doesn’t have the class instance self passed into it. Second the if statement should be if self.kwargs. Which is accessing the instance’s kwargs variable.

    def show(self):
            if self.kwargs:
                print(name, f"{key} and {value}" for key, value in self.kwargs.items())    # Using kwargs.items() didn't work too
    
            else:
                print(name)
    
            return self.kwargs