Type hint for Ellipsis
Asked Answered
C

1

7

How can I specify a type hint for a function that expects a literal Ellipsis (or ...) as an argument? In analogy with None, I'm tempted to write something like:

def f(x: Ellipsis):
    return

f(Ellipsis)

If I run this through mypy, however, I get:

1: error: Variable "builtins.Ellipsis" is not valid as a type

mypy is happy with the following:

import builtins

def f(x: builtins.ellipsis):
    return


f(Ellipsis)

But this fails at runtime with:

AttributeError: module 'builtins' has no attribute 'ellipsis'.
Chiefly answered 4/3, 2022 at 17:26 Comment(12)
a hack, but import builtins and try "builtins.Ellipsis" I could have sworn they were going to expose this type somewhere, but it would be in a very recent version of PythonTrilbi
In lieu of a proper type, Literal[Ellipsis] may do the jobStrontianite
import types; types.EllipsisType?Charactery
@Trilbi Tried that, mypy still complains...Chiefly
@Brian will give it a go.Chiefly
@Charactery ah, sounds like that's probably what I'm after.Chiefly
@Chiefly sorry, I meant "builtins.ellipsis", which could still be a workaround in Python < 3.10Trilbi
@Trilbi that's not importable, at least not from builtins, it just defined Ellipsis - I can't find anywhere that the class definition for <class 'ellipsis'> is actually exposed in python<3.10, which is of course the crux of the problem.Chiefly
@Chiefly You don't need to import it. You just need to use import builtins then use "builtins.ellipsis". AFAIKT, it works for mypy at least. That type wasn't exposed prior to Python 3.10, I'm pretty sureTrilbi
@Trilbi see the snippet in my question. You're right that mypy is satisfied, but the interpreter is not.Chiefly
@Chiefly the interpreter is fine with it. Please notice that I am suggesting you use the string "builtins.ellipsis".Trilbi
@Trilbi Ah, my brain silently dropped the quotes. Thanks!Chiefly
C
6

As suggested by jsbueno, the following works as of python 3.10:

from types import EllipsisType


def f(x: EllipsisType):
    return

f(Ellipsis)
Chiefly answered 5/3, 2022 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.