4

I have noticed a few functions' signatures with a / parameter. An example of this can be found in collections.Counter.__init__():

    def __init__(self, iterable=None, /, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.
        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
        '''
        super().__init__()
        self.update(iterable, **kwds)

I have not been able to find what it is used for and when I try to replicate it locally I get a SyntaxError.

Any information on what it is and why it is used would be appreciated.

Algebra8
  • 1,115
  • 1
  • 10
  • 23

2 Answers2

6

The is new syntax described at PEP570: usage of '/' to indicate that some function parameters must be specified positionally (i.e., cannot be used as keyword arguments).
Therefore separating the first argument that is passed by its location from the rest of the parameters which are passed to the dictionary.
Read more at Positional-Only Parameter.

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
3

It's new in Python 3.8. All arguments before the / are position-only arguments and cannot be specified using a keyword.

In the example given above, it is no longer legal to to write Counter(iterable=(1,2,3)).

See https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22