Page 1 of 1

I2C TypeError:extra positional arguments given

Posted: Thu Oct 29, 2020 11:56 am
by fmentiplay
This code works ...
>>>From machine import I2C, Pin
>>>i2c = I2C(scl=Pin(22), sda=Pin(21))

This code has error ...
>>>From machine import I2C, Pin
>>>scl = Pin(22)
>>>sda = Pin(21)
>>>i2c = I2C(scl, sda)
Traceback (most recent call last):
File "<stdin", line 1, in <module>
TypeError: extra positional arguments given

Why doesn't this work!! What is differnt about the two blocks of code?
Any help much apreciated
Frank

Re: I2C TypeError:extra positional arguments given

Posted: Thu Oct 29, 2020 12:24 pm
by jimmo
fmentiplay wrote:
Thu Oct 29, 2020 11:56 am
Why doesn't this work!! What is differnt about the two blocks of code?
The I2C class must take the "scl" and "sda" arguments as keyword arguments. This is common in a few places in MicroPython (and other Python libraries) for optional arguments, as it makes it easier to read the code that uses it (there's no guessing which one of the optional arguments it is).

To make the second example work, use scl=scl and sda=sda.

Code: Select all

>>>From machine import I2C, Pin
>>>scl = Pin(22)
>>>sda = Pin(21)
>>>i2c = I2C(scl=scl, sda=sda)
The equivalent in Python is:

Code: Select all

>>> def foo(x, *, y=0, z=0):
...   print(x, y, z)
... 
>>> 
>>> foo(1)
1 0 0
>>> foo(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes 1 positional argument but 3 were given
>>> foo(1, y=2, z=3)
1 2 3

Re: I2C TypeError:extra positional arguments given

Posted: Thu Oct 29, 2020 11:12 pm
by fmentiplay
Thank You for your very clear answer. Very much appreciated