PEP 637: Renamed file to rst and changed formatting of block code (#1619)

This commit is contained in:
Stefano Borini 2020-09-26 01:00:29 +01:00 committed by GitHub
parent ef4663634e
commit 8e16d32598
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 241 additions and 383 deletions

View File

@ -20,22 +20,17 @@ At present keyword arguments are allowed in function calls, but not in
item access. This PEP proposes that Python be extended to allow keyword item access. This PEP proposes that Python be extended to allow keyword
arguments in item access. arguments in item access.
The following example shows keyword arguments for ordinary function calls: The following example shows keyword arguments for ordinary function calls::
::
>>> val = f(1, 2, a=3, b=4) >>> val = f(1, 2, a=3, b=4)
The proposal would extend the syntax to allow a similar construct The proposal would extend the syntax to allow a similar construct
to indexing operations: to indexing operations::
::
>>> val = x[1, 2, a=3, b=4] # getitem >>> val = x[1, 2, a=3, b=4] # getitem
>>> x[1, 2, a=3, b=4] = val # setitem >>> x[1, 2, a=3, b=4] = val # setitem
>>> del x[1, 2, a=3, b=4] # delitem >>> del x[1, 2, a=3, b=4] # delitem
and would also provide appropriate semantics. and would also provide appropriate semantics.
This PEP is a successor to PEP 472, which was rejected due to lack of This PEP is a successor to PEP 472, which was rejected due to lack of
@ -79,56 +74,40 @@ The following practical use cases present different cases where a keyworded
specification would improve notation and provide additional value: specification would improve notation and provide additional value:
1. To provide a more communicative meaning to the index, preventing e.g. accidental 1. To provide a more communicative meaning to the index, preventing e.g. accidental
inversion of indexes inversion of indexes::
::
>>> grid_position[x=3, y=5, z=8] >>> grid_position[x=3, y=5, z=8]
>>> rain_amount[time=0:12, location=location] >>> rain_amount[time=0:12, location=location]
>>> matrix[row=20, col=40] >>> matrix[row=20, col=40]
2. To enrich the typing notation with keywords, especially during the use of generics::
2. To enrich the typing notation with keywords, especially during the use of generics
::
def function(value: MyType[T=int]): def function(value: MyType[T=int]):
3. In some domain, such as computational physics and chemistry, the use of a 3. In some domain, such as computational physics and chemistry, the use of a
notation such as ``Basis[Z=5]`` is a Domain Specific Language notation to represent notation such as ``Basis[Z=5]`` is a Domain Specific Language notation to represent
a level of accuracy a level of accuracy::
::
>>> low_accuracy_energy = computeEnergy(molecule, BasisSet[Z=3]) >>> low_accuracy_energy = computeEnergy(molecule, BasisSet[Z=3])
4. Pandas currently uses a notation such as 4. Pandas currently uses a notation such as::
::
>>> df[df['x'] == 1] >>> df[df['x'] == 1]
which could be replaced with df[x=1]. which could be replaced with ``df[x=1]``.
5. xarray has named dimensions. Currently these are handled with functions .isel: 5. xarray has named dimensions. Currently these are handled with functions .isel::
::
>>> data.isel(row=10) # Returns the tenth row >>> data.isel(row=10) # Returns the tenth row
which could also be replaced with `data[row=10]`. A more complex example: which could also be replaced with ``data[row=10]``. A more complex example::
::
>>> # old syntax >>> # old syntax
>>> da.isel(space=0, time=slice(None, 2))[...] = spam >>> da.isel(space=0, time=slice(None, 2))[...] = spam
>>> # new syntax >>> # new syntax
>>> da[space=0, time=:2] = spam >>> da[space=0, time=:2] = spam
Another example: Another example::
::
>>> # old syntax >>> # old syntax
>>> ds["empty"].loc[dict(lon=5, lat=6)] = 10 >>> ds["empty"].loc[dict(lon=5, lat=6)] = 10
@ -159,9 +138,7 @@ Subscripting ``obj[x]`` is, effectively, an alternate and specialised form of
function call syntax with a number of differences and restrictions compared to function call syntax with a number of differences and restrictions compared to
``obj(x)``. The current python syntax focuses exclusively on position to express ``obj(x)``. The current python syntax focuses exclusively on position to express
the index, and also contains syntactic sugar to refer to non-punctiform the index, and also contains syntactic sugar to refer to non-punctiform
selection (slices). Some common examples: selection (slices). Some common examples::
::
>>> a[3] # returns the fourth element of 'a' >>> a[3] # returns the fourth element of 'a'
>>> a[1:10:2] # slice notation (extract a non-trivial data subset) >>> a[1:10:2] # slice notation (extract a non-trivial data subset)
@ -185,16 +162,12 @@ violate this intrinsic meaning.
The second difference of the indexing notation compared to a function The second difference of the indexing notation compared to a function
is that indexing can be used for both getting and setting operations. is that indexing can be used for both getting and setting operations.
In python, a function cannot be on the left hand side of an assignment. In In python, a function cannot be on the left hand side of an assignment. In
other words, both of these are valid other words, both of these are valid::
::
>>> x = a[1, 2] >>> x = a[1, 2]
>>> a[1, 2] = 5 >>> a[1, 2] = 5
but only the first one of these is valid but only the first one of these is valid::
::
>>> x = f(1, 2) >>> x = f(1, 2)
>>> f(1, 2) = 5 # invalid >>> f(1, 2) = 5 # invalid
@ -208,19 +181,14 @@ arguments, unless the passed parameters are captured with \*args, in which case
they end up as entries in the args tuple. In other words, functions already they end up as entries in the args tuple. In other words, functions already
have anonymous argument semantic, exactly like the indexing operation. However, have anonymous argument semantic, exactly like the indexing operation. However,
__(get|set|del)item__ is not always receiving a tuple as the ``index`` argument __(get|set|del)item__ is not always receiving a tuple as the ``index`` argument
(to be uniform in behavior with \*args). In fact, given a trivial class: (to be uniform in behavior with \*args). In fact, given a trivial class::
::
class X: class X:
def __getitem__(self, index): def __getitem__(self, index):
print(index) print(index)
The index operation basically forwards the content of the square brackets "as is" The index operation basically forwards the content of the square brackets "as is"
in the ``index`` argument: in the ``index`` argument::
::
>>> x=X() >>> x=X()
>>> x[0] >>> x[0]
@ -240,27 +208,19 @@ in the ``index`` argument:
('hello', 'hi') ('hello', 'hi')
The fourth difference is that the indexing operation knows how to convert The fourth difference is that the indexing operation knows how to convert
colon notations to slices, thanks to support from the parser. This is valid colon notations to slices, thanks to support from the parser. This is valid::
::
a[1:3] a[1:3]
this one isn't this one isn't::
::
f(1:3) f(1:3)
The fifth difference is that there's no zero-argument form. This is valid The fifth difference is that there's no zero-argument form. This is valid::
::
f() f()
this one isn't this one isn't::
::
a[] a[]
@ -296,9 +256,7 @@ operation, may be used to take indexing decisions to obtain the final index, and
will have to accept values that are unconventional for functions. See for will have to accept values that are unconventional for functions. See for
example use case 1, where a slice is accepted. example use case 1, where a slice is accepted.
The new notation will make all of the following valid notation: The new notation will make all of the following valid notation::
::
>>> a[1] # Current case, single index >>> a[1] # Current case, single index
>>> a[1, 2] # Current case, multiple indexes >>> a[1, 2] # Current case, multiple indexes
@ -308,9 +266,7 @@ The new notation will make all of the following valid notation:
>>> a[3, R=3:10, K=4] # New case. Slice in keyword argument >>> a[3, R=3:10, K=4] # New case. Slice in keyword argument
>>> a[3, R=..., K=4] # New case. Ellipsis in keyword argument >>> a[3, R=..., K=4] # New case. Ellipsis in keyword argument
The new notation will NOT make the following valid notation: The new notation will NOT make the following valid notation::
::
>>> a[] # INVALID. No index and no keyword arguments. >>> a[] # INVALID. No index and no keyword arguments.
@ -326,15 +282,11 @@ Syntax and Semantics
The following old semantics are preserved: The following old semantics are preserved:
1. As said above, an empty subscript is still illegal, regardless of context. 1. As said above, an empty subscript is still illegal, regardless of context::
::
obj[] # SyntaxError obj[] # SyntaxError
2. A single index value remains a single index value when passed: 2. A single index value remains a single index value when passed::
::
obj[index] obj[index]
# calls type(obj).__getitem__(obj, index) # calls type(obj).__getitem__(obj, index)
@ -348,9 +300,7 @@ The following old semantics are preserved:
This remains the case even if the index is followed by keywords; see point 5 below. This remains the case even if the index is followed by keywords; see point 5 below.
3. Comma-seperated arguments are still parsed as a tuple and passed as 3. Comma-seperated arguments are still parsed as a tuple and passed as
a single positional argument: a single positional argument::
::
obj[spam, eggs] obj[spam, eggs]
# calls type(obj).__getitem__(obj, (spam, eggs)) # calls type(obj).__getitem__(obj, (spam, eggs))
@ -361,14 +311,11 @@ The following old semantics are preserved:
del obj[spam, eggs] del obj[spam, eggs]
# calls type(obj).__delitem__(obj, (spam, eggs)) # calls type(obj).__delitem__(obj, (spam, eggs))
The points above mean that classes which do not want to support keyword The points above mean that classes which do not want to support keyword
arguments in subscripts need do nothing at all, and the feature is therefore arguments in subscripts need do nothing at all, and the feature is therefore
completely backwards compatible. completely backwards compatible.
4. Keyword arguments, if any, must follow positional arguments. 4. Keyword arguments, if any, must follow positional arguments::
::
obj[1, 2, spam=None, 3] # SyntaxError obj[1, 2, spam=None, 3] # SyntaxError
@ -376,9 +323,7 @@ The following old semantics are preserved:
arguments give a SyntaxError. arguments give a SyntaxError.
5. Keyword subscripts, if any, will be handled like they are in 5. Keyword subscripts, if any, will be handled like they are in
function calls. Examples: function calls. Examples::
::
# Single index with keywords: # Single index with keywords:
@ -431,9 +376,7 @@ The following old semantics are preserved:
- but if no ``**kwargs`` parameter is defined, it is an error. - but if no ``**kwargs`` parameter is defined, it is an error.
7. Sequence unpacking remains a syntax error inside subscripts: 7. Sequence unpacking remains a syntax error inside subscripts::
::
obj[*items] obj[*items]
@ -445,18 +388,13 @@ The following old semantics are preserved:
This restriction has however been considered arbitrary by some, and it might This restriction has however been considered arbitrary by some, and it might
be lifted at a later stage for symmetry with kwargs unpacking, see next. be lifted at a later stage for symmetry with kwargs unpacking, see next.
8. Dict unpacking is permitted: 8. Dict unpacking is permitted::
::
items = {'spam': 1, 'eggs': 2} items = {'spam': 1, 'eggs': 2}
obj[index, **items] obj[index, **items]
# equivalent to obj[index, spam=1, eggs=2] # equivalent to obj[index, spam=1, eggs=2]
9. Keyword-only subscripts are permitted. The positional index will be the empty tuple::
9. Keyword-only subscripts are permitted. The positional index will be the empty tuple:
::
obj[spam=1, eggs=2] obj[spam=1, eggs=2]
# calls type(obj).__getitem__(obj, (), spam=1, eggs=2) # calls type(obj).__getitem__(obj, (), spam=1, eggs=2)
@ -467,10 +405,7 @@ The following old semantics are preserved:
del obj[spam=1, eggs=2] del obj[spam=1, eggs=2]
# calls type(obj).__delitem__(obj, (), spam=1, eggs=2) # calls type(obj).__delitem__(obj, (), spam=1, eggs=2)
10. Keyword arguments must allow slice syntax::
10. Keyword arguments must allow slice syntax.
::
obj[3:4, spam=1:4, eggs=2] obj[3:4, spam=1:4, eggs=2]
# calls type(obj).__getitem__(obj, slice(3, 4, None), spam=slice(1, 4, None), eggs=2) # calls type(obj).__getitem__(obj, slice(3, 4, None), spam=slice(1, 4, None), eggs=2)
@ -478,17 +413,12 @@ The following old semantics are preserved:
This may open up the possibility to accept the same syntax for general function This may open up the possibility to accept the same syntax for general function
calls, but this is not part of this recommendation. calls, but this is not part of this recommendation.
11. Keyword arguments must allow Ellipsis 11. Keyword arguments must allow Ellipsis::
::
obj[..., spam=..., eggs=2] obj[..., spam=..., eggs=2]
# calls type(obj).__getitem__(obj, Ellipsis, spam=Ellipsis, eggs=2) # calls type(obj).__getitem__(obj, Ellipsis, spam=Ellipsis, eggs=2)
12. Keyword arguments allow for default values::
12. Keyword arguments allow for default values
::
# Given type(obj).__getitem__(obj, index, spam=True, eggs=2) # Given type(obj).__getitem__(obj, index, spam=True, eggs=2)
obj[3] # Valid. index = 3, spam = True, eggs = 2 obj[3] # Valid. index = 3, spam = True, eggs = 2
@ -517,15 +447,11 @@ Corner case and Gotchas
With the introduction of the new notation, a few corner cases need to be analysed: With the introduction of the new notation, a few corner cases need to be analysed:
1. Technically, if a class defines their getter like this: 1. Technically, if a class defines their getter like this::
::
def __getitem__(self, index): def __getitem__(self, index):
then the caller could call that using keyword syntax, like these two cases: then the caller could call that using keyword syntax, like these two cases::
::
obj[3, index=4] obj[3, index=4]
obj[index=1] obj[index=1]
@ -540,18 +466,13 @@ With the introduction of the new notation, a few corner cases need to be analyse
backward compatibility issues on this respect. backward compatibility issues on this respect.
Classes that wish to stress this behavior explicitly can define their Classes that wish to stress this behavior explicitly can define their
parameters as positional-only: parameters as positional-only::
::
def __getitem__(self, index, /): def __getitem__(self, index, /):
2. a similar case occurs with setter notation 2. a similar case occurs with setter notation::
::
# Given type(obj).__getitem__(self, index, value): # Given type(obj).__getitem__(self, index, value):
obj[1, value=3] = 5 obj[1, value=3] = 5
This poses no issue because the value is passed automatically, and the python interpreter will raise This poses no issue because the value is passed automatically, and the python interpreter will raise
@ -560,31 +481,22 @@ With the introduction of the new notation, a few corner cases need to be analyse
3. If the subscript dunders are declared to use positional-or-keyword 3. If the subscript dunders are declared to use positional-or-keyword
parameters, there may be some surprising cases when arguments are passed parameters, there may be some surprising cases when arguments are passed
to the method. Given the signature: to the method. Given the signature::
::
def __getitem__(self, index, direction='north') def __getitem__(self, index, direction='north')
if the caller uses this: if the caller uses this::
::
obj[0, 'south'] obj[0, 'south']
they will probably be surprised by the method call: they will probably be surprised by the method call::
::
# expected type(obj).__getitem__(0, direction='south') # expected type(obj).__getitem__(0, direction='south')
# but actually get: # but actually get:
obj.__getitem__((0, 'south'), direction='north') obj.__getitem__((0, 'south'), direction='north')
Solution: best practice suggests that keyword subscripts should be Solution: best practice suggests that keyword subscripts should be
flagged as keyword-only when possible: flagged as keyword-only when possible::
::
def __getitem__(self, index, *, direction='north') def __getitem__(self, index, *, direction='north')
@ -592,14 +504,11 @@ With the introduction of the new notation, a few corner cases need to be analyse
where this is the desired behaviour. But linters may choose to warn where this is the desired behaviour. But linters may choose to warn
about subscript methods which don't use the keyword-only flag. about subscript methods which don't use the keyword-only flag.
4. As we saw, a single value followed by a keyword argument will not be changed into a tuple, i.e.: 4. As we saw, a single value followed by a keyword argument will not be changed into a tuple, i.e.:
``d[1, a=3]`` is treated as ``__getitem__(1, a=3)``, NOT ``__getitem__((1,), a=3)``. It would be ``d[1, a=3]`` is treated as ``__getitem__(1, a=3)``, NOT ``__getitem__((1,), a=3)``. It would be
extremely confusing if adding keyword arguments were to change the type of the passed index. extremely confusing if adding keyword arguments were to change the type of the passed index.
In other words, adding a keyword to a single-valued subscript will not change it into a tuple. In other words, adding a keyword to a single-valued subscript will not change it into a tuple.
For those cases where an actual tuple needs to be passed, a proper syntax will have to be used: For those cases where an actual tuple needs to be passed, a proper syntax will have to be used::
::
obj[(1,), a=3] # calls __getitem__((1,), a=3) obj[(1,), a=3] # calls __getitem__((1,), a=3)
@ -609,27 +518,21 @@ With the introduction of the new notation, a few corner cases need to be analyse
Note that this behavior just reveals the truth that the ``obj[1,]`` notation is shorthand for Note that this behavior just reveals the truth that the ``obj[1,]`` notation is shorthand for
``obj[(1,)]`` (and also ``obj[1]`` is shorthand for ``obj[(1)]``, with the expected behavior). ``obj[(1,)]`` (and also ``obj[1]`` is shorthand for ``obj[(1)]``, with the expected behavior).
When keywords are present, the rule that you can omit this outermost pair of parentheses is no When keywords are present, the rule that you can omit this outermost pair of parentheses is no
longer true. longer true::
::
obj[1] # calls __getitem__(1) obj[1] # calls __getitem__(1)
obj[1, a=3] # calls __getitem__(1, a=3) obj[1, a=3] # calls __getitem__(1, a=3)
obj[1,] # calls __getitem__((1,)) obj[1,] # calls __getitem__((1,))
obj[(1,), a=3] # calls __getitem__((1,), a=3) obj[(1,), a=3] # calls __getitem__((1,), a=3)
This is particularly relevant in the case where two entries are passed: This is particularly relevant in the case where two entries are passed::
::
obj[1, 2] # calls __getitem__((1, 2)) obj[1, 2] # calls __getitem__((1, 2))
obj[(1, 2)] # same as above obj[(1, 2)] # same as above
obj[1, 2, a=3] # calls __getitem__((1, 2), a=3) obj[1, 2, a=3] # calls __getitem__((1, 2), a=3)
obj[(1, 2), a=3] # calls __getitem__((1, 2), a=3) obj[(1, 2), a=3] # calls __getitem__((1, 2), a=3)
And particularly when the tuple is extracted as a variable: And particularly when the tuple is extracted as a variable::
::
t = (1, 2) t = (1, 2)
obj[t] # calls __getitem__((1, 2)) obj[t] # calls __getitem__((1, 2))
@ -663,7 +566,6 @@ to invoke the old functions. We propose ``BINARY_SUBSCR_EX``,
have to generate these new opcodes. The ``PyObject_(Get|Set|Del)Item`` implementations have to generate these new opcodes. The ``PyObject_(Get|Set|Del)Item`` implementations
will call the extended methods passing ``NULL`` as kwargs. will call the extended methods passing ``NULL`` as kwargs.
Workarounds Workarounds
=========== ===========
@ -680,68 +582,52 @@ be universal. For example, a module or package might require the use of its own
helpers. helpers.
1. User defined classes can be given ``getitem`` and ``delitem`` methods, 1. User defined classes can be given ``getitem`` and ``delitem`` methods,
that respectively get and delete values stored in a container. that respectively get and delete values stored in a container::
::
>>> val = x.getitem(1, 2, a=3, b=4) >>> val = x.getitem(1, 2, a=3, b=4)
>>> x.delitem(1, 2, a=3, b=4) >>> x.delitem(1, 2, a=3, b=4)
The same can't be done for ``setitem``. It's not valid syntax. The same can't be done for ``setitem``. It's not valid syntax::
::
>>> x.setitem(1, 2, a=3, b=4) = val >>> x.setitem(1, 2, a=3, b=4) = val
SyntaxError: can't assign to function call SyntaxError: can't assign to function call
2. A helper class, here called ``H``, can be used to swap the container 2. A helper class, here called ``H``, can be used to swap the container
and parameter roles. In other words, we use and parameter roles. In other words, we use::
::
H(1, 2, a=3, b=4)[x] H(1, 2, a=3, b=4)[x]
as a substitute for as a substitute for::
::
x[1, 2, a=3, b=4] x[1, 2, a=3, b=4]
This method will work for ``getitem``, ``delitem`` and also for This method will work for ``getitem``, ``delitem`` and also for
``setitem``. This is because ``setitem``. This is because::
::
>>> H(1, 2, a=3, b=4)[x] = val >>> H(1, 2, a=3, b=4)[x] = val
is valid syntax, which can be given the appropriate semantics. is valid syntax, which can be given the appropriate semantics.
3. A helper function, here called ``P``, can be used to store the 3. A helper function, here called ``P``, can be used to store the
arguments in a single object. For example arguments in a single object. For example::
::
>>> x[P(1, 2, a=3, b=4)] = val >>> x[P(1, 2, a=3, b=4)] = val
is valid syntax, and can be given the appropriate semantics. is valid syntax, and can be given the appropriate semantics.
4. The ``lo:hi:step`` syntax for slices is sometimes very useful. This 4. The ``lo:hi:step`` syntax for slices is sometimes very useful. This
syntax is not directly available in the work-arounds. However syntax is not directly available in the work-arounds. However::
::
s[lo:hi:step] s[lo:hi:step]
provides a work-around that is available everything, where provides a work-around that is available everything, where::
::
class S: class S:
def __getitem__(self, key): return key def __getitem__(self, key): return key
s = S() s = S()
defines the helper object `s`. defines the helper object ``s``.
Rejected Ideas Rejected Ideas
============== ==============
@ -771,15 +657,11 @@ that are invoked over the ``__(get|set|del)item__`` triad, if they are present.
The rationale around this choice is to make the intuition around how to add kwd The rationale around this choice is to make the intuition around how to add kwd
arg support to square brackets more obvious and in line with the function arg support to square brackets more obvious and in line with the function
behavior. Given: behavior. Given::
::
def __getitem_ex__(self, x, y): ... def __getitem_ex__(self, x, y): ...
These all just work and produce the same result effortlessly: These all just work and produce the same result effortlessly::
::
obj[1, 2] obj[1, 2]
obj[1, y=2] obj[1, y=2]
@ -813,12 +695,10 @@ The problems with this approach were found to be:
- it would potentially lead to mixed situations where the extended version is - it would potentially lead to mixed situations where the extended version is
defined for the getter, but not for the setter. defined for the getter, but not for the setter.
- In the __setitem_ex__ signature, value would have to be made the first - In the ``__setitem_ex__`` signature, value would have to be made the first
element, because the index is of arbitrary length depending on the specified element, because the index is of arbitrary length depending on the specified
indexes. This would look awkward because the visual notation does not match indexes. This would look awkward because the visual notation does not match
the signature: the signature::
::
obj[1, 2] = 3 # calls obj.__setitem_ex__(3, 1, 2) obj[1, 2] = 3 # calls obj.__setitem_ex__(3, 1, 2)
@ -842,9 +722,7 @@ Has problems similar to the above.
create a new "kwslice" object create a new "kwslice" object
----------------------------- -----------------------------
This proposal has already been explored in "New arguments contents" P4 in PEP 472. This proposal has already been explored in "New arguments contents" P4 in PEP 472::
::
obj[a, b:c, x=1] # calls __getitem__(a, slice(b, c), key(x=1)) obj[a, b:c, x=1] # calls __getitem__(a, slice(b, c), key(x=1))
@ -858,22 +736,16 @@ make sense and which ones do not.
Using a single bit to change the behavior Using a single bit to change the behavior
----------------------------------------- -----------------------------------------
A special class dunder flag A special class dunder flag::
::
__keyfn__ = True __keyfn__ = True
would change the signature of the ``__get|set|delitem__`` to a "function like" dispatch, would change the signature of the ``__get|set|delitem__`` to a "function like" dispatch,
meaning that this meaning that this::
::
>>> d[1, 2, z=3] >>> d[1, 2, z=3]
would result in a call to would result in a call to::
::
>>> d.__getitem__(1, 2, z=3) # instead of d.__getitem__((1, 2), z=3) >>> d.__getitem__(1, 2, z=3) # instead of d.__getitem__((1, 2), z=3)
@ -916,34 +788,26 @@ Use None instead of the empty tuple when no positional index is given
The case ``obj[k=3]`` will lead to a call ``__getitem__((), k=3)``. The case ``obj[k=3]`` will lead to a call ``__getitem__((), k=3)``.
The alternative ``__getitem__(None, k=3)`` was considered but rejected: The alternative ``__getitem__(None, k=3)`` was considered but rejected:
NumPy uses `None` to indicate inserting a new axis/dimensions (there's NumPy uses `None` to indicate inserting a new axis/dimensions (there's
a ``np.newaxis`` alias as well): a ``np.newaxis`` alias as well)::
::
arr = np.array(5) arr = np.array(5)
arr.ndim == 0 arr.ndim == 0
arr[None].ndim == arr[None,].ndim == 1 arr[None].ndim == arr[None,].ndim == 1
So the final conclusion is that we favor the following series: So the final conclusion is that we favor the following series::
::
obj[k=3] # __getitem__((), k=3). Empty tuple obj[k=3] # __getitem__((), k=3). Empty tuple
obj[1, k=3] # __getitem__(1, k=3). Integer obj[1, k=3] # __getitem__(1, k=3). Integer
obj[1, 2, k=3] # __getitem__((1, 2), k=3). Tuple obj[1, 2, k=3] # __getitem__((1, 2), k=3). Tuple
more than this: more than this::
::
obj[k=3] # __getitem__(None, k=3). None obj[k=3] # __getitem__(None, k=3). None
obj[1, k=3] # __getitem__(1, k=3). Integer obj[1, k=3] # __getitem__(1, k=3). Integer
obj[1, 2, k=3] # __getitem__((1, 2), k=3). Tuple obj[1, 2, k=3] # __getitem__((1, 2), k=3). Tuple
With the first more in line with a \*args semantics for calling a routine with With the first more in line with a \*args semantics for calling a routine with
no positional arguments no positional arguments::
::
>>> def foo(*args, **kwargs): >>> def foo(*args, **kwargs):
... print(args, kwargs) ... print(args, kwargs)
@ -951,9 +815,7 @@ no positional arguments
>>> foo(k=3) >>> foo(k=3)
() {'k': 3} () {'k': 3}
Although we accept the following asymmetry: Although we accept the following asymmetry::
::
>>> foo(1, k=3) >>> foo(1, k=3)
(1,) {'k': 3} (1,) {'k': 3}
@ -971,16 +833,12 @@ Common objections
One problem is type hint creation has been extended to built-ins in python 3.9, One problem is type hint creation has been extended to built-ins in python 3.9,
so that you do not have to import Dict, List, et al anymore. so that you do not have to import Dict, List, et al anymore.
Without kwdargs inside ``[]``, you would not be able to do this: Without kwdargs inside ``[]``, you would not be able to do this::
::
Vector = dict[i=float, j=float] Vector = dict[i=float, j=float]
but for obvious reasons, call syntax using builtins to create custom type hints but for obvious reasons, call syntax using builtins to create custom type hints
isn't an option: isn't an option::
::
dict(i=float, j=float) # would create a dictionary, not a type dict(i=float, j=float) # would create a dictionary, not a type