Python raises a TypeError when a function call passes a keyword argument the function’s signature does not accept. The traceback names the offending argument so you can fix the call site, the function definition, or both.

Reproducing the error

Define calculate with one positional parameter and call it with an extra keyword argument:

import math

def calculate(num):
    return math.factorial(num)

ans = calculate(4, count=0)
print(ans)

Running this script raises:

Traceback (most recent call last):
  File "/tmp/typeerror_test.py", line 4, in 
    ans = calculate(4, count=0)
TypeError: calculate() got an unexpected keyword argument 'count'

The traceback points to the exact line and argument. count is the keyword that triggered the error.

Method 1: Add **kwargs to the signature

Accept any extra keyword argument by adding **kwargs to the function definition. kwargs becomes a dict inside the function body, and you can use it or ignore it:

import math

def calculate(num, **kwargs):
    return math.factorial(num)

ans = calculate(4, count=0)
print(ans)

Use this approach when the call site is fixed and the function genuinely should accept arbitrary keyword arguments. The original count value is dropped unless you read it from kwargs.

Method 2: Use the argument at the call site

If calculate is meant to use count for something, add it to the signature directly:

import math

def calculate(num, count=1):
    return math.factorial(num) * count

ans = calculate(4, count=3)
print(ans)

The error disappears because count is now a named parameter with a default value of 1. Use this when the keyword is meaningful and you want it to participate in the function logic.

Method 3: Remove the unwanted keyword

If count is a leftover from a previous version of the function, fix the call site rather than the signature:

import math

def calculate(num):
    return math.factorial(num)

ans = calculate(4)
print(ans)

Drop the keyword at the call site when it is genuinely unused. A function that does not need an argument should not accept one.

Diagnosing the error from the traceback

Three things to read in a TypeError traceback:

  • The function name. The error says which function rejected the argument.
  • The argument name. The error says which keyword was unexpected.
  • The call site. The error points to the line that made the call.

Once you have those three pieces, the fix is one of: align the call, accept the keyword, or drop it. For deeper help, inspect() from the inspect module prints a function’s signature so you can see what it actually expects:

import inspect
print(inspect.signature(calculate))

Signature (num) tells you calculate takes a single positional argument, which is exactly the source of the error when the call site passes count=0.

Share.
Leave A Reply