Search code examples
pythonclassarguments

Is it possible to make class or function with variable number of arguments without using *args or default values?(like in range function)


I want to create class that has min and max value with default min being set to 0. I want it to have possibility to set only max value or both max and min with min value first and max second. Basically I want it to receive arguments like range function does. I don't want to use *args because I want arguments to show while using help() and in my programming environment when I hover cursor over class name. I know I could make both min and max have default values but I really want to know if it is possible to make it work like range.

Is it possible to replicate how arguments in range work or is it possible only because range is not written in python?

I tried to replicate how variables in range works but documentation doesn't mention anything about these two sets of variables and I am not experienced enough to find what I'm looking for in source code. Even though I knew python overrides declaration of a class or function with new one if both has the same name I tried writing two init methods but this obviously didn't work. I also tried the same with two classes with the same name and two functions, in both cases I got the same result.


Solution

  • Note that the documentation lists two different versions of range:

    class range(stop)
    class range(start, stop[, step])
    

    There's no way to implement literally two versions like this in Python, there can only be a single implementation, which will have to figure out its arguments internally:

    def range(start, stop=None, step=None):
        if stop is None:
            stop = start
        ...
    

    You can dress this up to appear with two very different signatures using typing.overload:

    @overload
    def range(stop):
        ...
    
    @overload
    def range(start, stop, step=None):
        ...
    
    def range(start, stop=None, step=None):
        if stop is None:
            stop = start
        ...