Giuppox
Giuppox

Reputation: 1631

Get python ellipsis (...) type without having to define it as `type(...)`

Is there a way to get python's Ellipsis type? I saw that doing type(Ellipsis) and type(...) returns <class 'ellipsis'>, but by writing x = ellipsis() it seems like if ellipsis is not a default-defined data type (NameError: name 'ellipsis' is not defined).
I thought builtins builtin module could provide the solution to my problem, but the following also raises error.

import builtins
_ellipsis = builtins.ellipsis    # AttributeError: module 'builtins' has no attribute 'ellipsis'

What i actually need it, is for doing something like this:

from typing import Union

def f(x: Union[str, type(...)]):
    pass

Obviously the previous works, but i'd like to have a more fancier solution that just type(...)

Upvotes: 1

Views: 2777

Answers (2)

ForceBru
ForceBru

Reputation: 44888

According to the documentation:

Ellipsis

The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types. Ellipsis is the sole instance of the types.EllipsisType type.

So, in Python 3.10 (!) you can use types.EllipsisType to represent this type.

Otherwise, you can define your own variable like this:

EllipsisType = type(...)

And then use it in type declarations

Upvotes: 5

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96236

For now, what you are doing is the only way to get at it.

In Python 3.10, it will be available in the types module.

3.10 also added NoneType here, and NotImplementedType.

Upvotes: 0

Related Questions