Type()(), snippet

hello,

I wonder what is this doing,
I originally found this kind of snippet in Ellipsis documentation Built-in Types — Python 3.11.0 documentation .
It says it produces the Ellipsis singleton.
Which would need some explanation to me, but anyways, I find it interesting:

Try it in the interpreter:

... # Ellipsis
type(Ellipsis)
type(Ellipsis)()

or with other types:

n = 4
type(n)
type(n)()
s = "abc"
type(s)
type(s)()
1 Like

What you’re doing is requesting a default object of the same type as something else. A default integer is zero; a default string is the empty string. There’s only one instance of Ellipsis, so when you request the default object of that type, you get Ellipsis. Which is exactly the same object you started with, making it mostly useless.

2 Likes

It’s a combination of two call operations. First type(x) returns the class of the object you give it - type("hi") gives str, type([]) gives list, etc. All objects must have a class, so type(Ellipsis) gives the very imaginatively named types.EllipsisType class. The second set of parentheses then calls the class with no arguments. Calling a class creates a new object, and usually classes can be called with no arguments to give a default/empty object. str() returns "", dict() gives {} and int() gives 0. So type(obj)() is a way to take any object, and try to return a new blank version of it.

Since Ellipsis is a “singleton” class (only one instance is allowed to exist), the class takes no parameters, and gives you back the existing object if you try calling it to construct more. The same thing happens with None and NotImplemented.

2 Likes

awesome, thank you!