I2C TypeError:extra positional arguments given

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
fmentiplay
Posts: 7
Joined: Fri Feb 14, 2020 12:10 am

I2C TypeError:extra positional arguments given

Post by fmentiplay » Thu Oct 29, 2020 11:56 am

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

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: I2C TypeError:extra positional arguments given

Post by jimmo » Thu Oct 29, 2020 12:24 pm

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

fmentiplay
Posts: 7
Joined: Fri Feb 14, 2020 12:10 am

Re: I2C TypeError:extra positional arguments given

Post by fmentiplay » Thu Oct 29, 2020 11:12 pm

Thank You for your very clear answer. Very much appreciated

Post Reply