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

2
  • 3
    Those are just warning because those variables have type annotations, and they are not marked as Optional making it wrong to set them as None. Change the annotations to be Optional[<type>] and those warning should go away Commented Mar 13, 2021 at 5:55
  • Why do you think your static type checker wouldn't complain if you tried to assign a value of the wrong type? Commented Mar 13, 2021 at 23:50

1 Answer 1

4

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: ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.