Skip to content

Type inference and hasattr #1424

Closed
@JukkaL

Description

@JukkaL

I just encountered code like this:

if hasattr(x, 'initialize'):
     x.initialize()

The type of x was an ABC but it doesn't include initialize. This can be easily worked around by rewriting it like this:

if hasattr(x, 'initialize'):
     cast(Any, x).initialize()

However, mypy could do better, plausibly. For example:

  • If x has a union type, infer only union item types with attribute initialize after the hasattr check. So if type of x is Union[str, X] and X has initialize, infer type of x to be X in the if body.
  • Allow specifying "potentially undefined" attributes in types. Accessing these requires a hasattr check (a little like Optional[...] requiring something like an is not None check). Not sure what the syntax for this would be like. It would be nice to support these in ABCs as well.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions