Missing Required Positional Argument

3.1k views Asked by At

In my program, I am trying to find if a certain variable is in a list. However, I keep getting the following error and I am very stuck on how to get past it:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\mikey\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "G:\My Drive\DGT301\Python\AS\order.py", line 171, in confirm_order
    self.check(self.order_item, self.food_list)
TypeError: check() missing 1 required positional argument: 'self'

Here is my code:

def find(thing, list3d):
    for x in list3d:
         for y in x:
            if y[1] == thing:
                return True
    return False

def check(item, list3d, result, self):
    self.result = 'found' if self.find(item, list3d) else 'not found'
    print(f'{item} was {result}')

def confirm_order(self):
    self.order_item = self.r.get()
    self.check(self.order_item, self.food_list)
    

I tried putting "self." before all the variables and tried removing some and the error stays the same.

2

There are 2 answers

0
TallChuck On

When you call a method on an object, the Python interpreter will automatically insert a reference to that object as the first positional argument. To handle this, the first argument for a method (a function defined inside a class) conventionally calls the first argument self. Your functions are not defined inside of a class, so the use of self doesn't make sense.

0
EvillerBob On

In addition to the existing answers, you have also added self to the end of the parameter list for check() which is the specific cause of the error. Your function is expecting four parameters def check(item, list3d, result, self) but the function calling it is only passing two: self.check(self.order_item, self.food_list)

...actually, why is the error code only reporting 1 missing parameter instead of 2? result should be missing as well? Maybe there's some python magic there I don't understand...

def check(item, list3d, result, self):

    # four parameters expected by the function ^^^

    self.result = 'found' if self.find(item, list3d) else 'not found'
    print(f'{item} was {result}')

def confirm_order(self):
    self.order_item = self.r.get()
    self.check(self.order_item, self.food_list)

    # Only two parameters being sent to the function ^^^

If these functions are actually part of a class, then you will need to put it as the first parameter in each function within the class, but basically ignore it when calling the function.

For example:

def check(self,item,list3d,result):
    #etc., etc.

def confirm_order(self):
    self.check(item,list3d,result)