I am trying to pass a data class object as a optional parameter to a function, but got stuck. So, here is a simplified code describing the problem. First, I am defining a data class:
@dataclass
class SomeObject:
A: str
If i make the parameter non-optional, there is no problem:
def printObject0 (Index, AnyObject):
print(Index, AnyObject.A)
Object1 = SomeObject ("A")
printObject0 (1, Object1)
# gives:
# 1 A
However, if i try to make it an optional parameter *args like this...
def printObject1 (Index, *AnyObject):
print(Index, AnyObject.A)
Object1 = SomeObject ("A")
printObject1 (1, Object1)
# gives:
# AttributeError: 'tuple' object has no attribute 'A'
...or with **kwargs like this...
def printObject2 (Index, **AnyObject):
print(Index, AnyObject.A)
Object1 = SomeObject ("A")
printObject2 (1, Object1)
# gives:
# TypeError: printObject2() takes 1 positional argument but 2 were given
i get the above-stated errors.
Does anyone have an idea how i can make the object optional?
The function argument
*AnyObject
means theAnyObject
is a tuple of all remaining positional arguments. So you can doFurthermore, the function argument
**AnyObject
means thatAnyObject
is a dictionary of all remaining keyword arguments. So you can do:BTW: Usually, optional function arguments have default values, like
Normally, the second function call should be avoided because it is more error-prone.
But since the default argument value is mutable in this case (see below) it is safer to do
The problem with
printObject_3
is that you can change the default value inside the function:The reason for that unexpected behavior is that the default value is mutable. Therefore, use the pattern in
printObject_4
when you want to use mutable default values or be careful and dont write to the keyword argument.