Search code examples
pythonpython-3.xpycharmnonetypepython-typing

How can I initialize an object with a null value in Python?


class FileCompoundDefinition(AbstractCompoundDefinition):
    # <editor-fold desc="(type declaration)">
    __include_dependency_graph: IncludeDepGraphTagFL
    __inner_namespace: InnerNamespaceTag
    __brief_description: BriefDescription
    __detailed_description: DetailedDescription
    __location: LocationDefinitionCL
    # </editor-fold>

    # <editor-fold desc="(constructor)">
    def __init__(self,
                 id: str,
                 kind: str,
                 language: str,
                 compound_name: str):
        super().__init__(id, kind, compound_name)
        self.__language = language
        self.__includes_list = []
        self.__inner_class_list = []
        self.__include_dependency_graph = None
        self.__inner_namespace = None
        self.__brief_description = None
        self.__detailed_description = None
        self.__location = None
    # </editor-fold>

In the above source code, the following lines are showing errors:

self.__include_dependency_graph = None
self.__inner_namespace = None
self.__brief_description = None
self.__detailed_description = None
self.__location = None

enter image description here

How can I initialize an object with a None value?


Solution

  • Use typing.Optional the following doesn't cause any warnings.

    from typing import Optional
    
    class FileCompoundDefinition(AbstractCompoundDefinition):
    
        __location: Optional[LocationDefinitionCL]
    
        def __init__(...)
    
        self.__location = None
        ...
        self.__location = LocationDefinitionCL()
    

    See

    PEP 484 - Union types

    As a shorthand for Union[T1, None] you can write Optional[T1]; for example, the above is equivalent to:

    from typing import Optional
    
    def handle_employee(e: Optional[Employee]) -> None: ...