user3848207
user3848207

Reputation: 4917

How to give type annotation for empty set?

I have this line in python;

set1 = set()  # create empty set

When I use mypy to scan, I get the error Need type annotation for 'set1'

How do I give type annotation for empty set?

I am using python 3.7 and mypy plugin in pycharm.

Upvotes: 5

Views: 3168

Answers (3)

Sam Bull
Sam Bull

Reputation: 3229

Both of the previous answers are incorrect. An annotation of set is exactly the same as set[Any], which means any set would be valid.

The correct answer is that there is no way to type an empty set. The best recommendation currently is to use set[object], which atleast will result in a type error for most operations if someone tries to use values from it. See some discussion, for example, at https://github.com/python/typing/issues/157

There are some incidental methods that can be used to type certain other empty types though, such as:

EmptyString = Literal[""]
EmptyTuple = tuple[()]

class EmptyDict(TypedDict):
    """Empty dict for typing."""

Upvotes: 2

Andrey Khoronko
Andrey Khoronko

Reputation: 673

Simple version: set1: set = set()

More specific version:

from typing import Set
set1: Set[<type>] = set()

e.g. for set of strings: set1: Set[str] = set()

Upvotes: 12

chepner
chepner

Reputation: 531275

I'm not sure what is requiring a type annotation, but that annotation would simply be

set1: set = set()

Upvotes: 3

Related Questions