4
I was looking at the documentation (docstring) of the range function and came across the following:
Init signature: range(self, /, *args, **kwargs)
Docstring:
range(stop) -> range object
range(start, stop[, step]) -> range object
My understanding is that the function range()
takes both positional arguments (a tuple or list) and keyword arguments (dictionary).
Testing, I managed to do the following:
# passando argumentos da forma padrão:
for i in range(0, 10, 1):
print(i)
Returns sequence 1 to 10 with step 1.
# passando argumentos como uma lista:
for i in range(*[1, 10, 2]):
print(i)
Using the *
as an "unpacking" indicator, the range resolves and returns an iterable with: 1, 3, 5, 7, 9.
And if I wanted to pass a dictionary, as below?
for i in range(**{'start':0, 'stop':100, 'step':10}):
print(i)
While executing the above code I take an error:
Typeerror: range() takes no keyword argumentsrangeRange
It’s a docstring error, or you don’t even have a way to pass **kwargs
for the range?
In which version of Python did you see this? As far as I know this is not possible. In time in version 3.8.1 the docstring is different
– Paulo Marques
There’s no way to do it, but idle people always invent their tricks
for i in range(*{'start':0, 'stop':100, 'step':10}.values()): print(i)
– Augusto Vasques
@Augusto Vasques, in this case, what is passed to the range is a tuple, generated from the dictionary. There is guarantee that the values brought by the method
dict.values()
will always be in the order they were declared?– LuizAngioletti
Modified in version 3.7: Dictionary order is guaranteed according to insertion order. This behavior was a detail of Cpython’s implementation from version 3.6 onwards. Ref: https://docs.python.org/pt-br/3/library/stdtypes.html#Mapping-types-Dict , but still a gambiarra as it is verbose code for a simple operation.
– Augusto Vasques
@Paulomarques, the version I saw this docstring was in 3.9.1
– LuizAngioletti