user366312
user366312

Reputation: 17008

How can I pass a null value to a string parameter in Python?

class MyClass:
    def __init__(self, name: str):
        self.__name = name
        

my_obj = MyClass(None)

I am getting the following error/warning:

enter image description here

How can I pass a null value to a string parameter in Python?

Upvotes: 1

Views: 5247

Answers (1)

onlyphantom
onlyphantom

Reputation: 9603

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

In the following code, you've set typing on the name parameter to be str. None is not a str (string) since it belongs to its own NoneType.

class MyClass:
    def __init__(self, name: str):
        self.__name = name
        
my_obj = MyClass(None)

You can instead use the Union if you want to accept strings, but also allow for the None type:

from typing import Union
class MyClass:
    def __init__(self, name: Union[str, None]):
        self.__name = name
        
my_obj = MyClass(None)

In Python 3.10, you can also write: str | None. You can read PEP 604, docs linked here.

An alternative is the Optional:

class MyClass:
    def __init__(self, name: Optional[str] = None):
        self.__name = name

Upvotes: 3

Related Questions