1
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?

1
  • 2
    Can't you just create an empty constructor? Or use default arguments? Commented Mar 13, 2021 at 9:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why not using Optional?
If you looked at my revision history, the first version of edit suggested Optional. I re-read the OP's question and felt (maybe wrongly) that he would appreciate the str | None because it's more explicit. Added Optional solution anyway. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.