Equivalent __index__ method in Micropython

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
MicroP_W691
Posts: 10
Joined: Mon Mar 09, 2020 10:47 am

Equivalent __index__ method in Micropython

Post by MicroP_W691 » Tue Apr 28, 2020 11:38 am

In CPython, there is a class 'magic' method '__index__()' which allows the object to be used in slice notation:

Code: Select all

class Screen_Object(object):
	def __init__(x_pos, y_pos, index)
		self.x = x_pos
		self.y = y_pos
		self.screen_list_index = index
		
	def draw_object(self):
		#draw instructions
	
	def __index__(self):
		return self.screen_list_index
 
title = Screen_Object(200,200, 1)
all_screen_objects = ['background', 'title', 'text', 'icon']


>>> all_screen_objects[title]
'title'
I tried to replicate this in Micropython but it seems it does not use the same method for slicing or indexing. I could add an

Code: Select all

 '__int__()' 
method to my class, and then call

Code: Select all

all_screen_objects[int(title)]
but that is just as messy as

Code: Select all

all_screen_objects[title.screen_list_index]
Can someone explain what methods are called when an object is used as an index? Or is it simply that it type-checks the object to make sure its an integer and then just gets the value?

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

Re: Equivalent __index__ method in Micropython

Post by jimmo » Tue Apr 28, 2020 12:01 pm

Unfortunately, support for __index__ is not implemented in MicroPython. It appears that this is not documented in the "Differences from CPython" docs, I will send a PR to add that soon. http://docs.micropython.org/en/latest/genrst/index.html
MicroP_W691 wrote:
Tue Apr 28, 2020 11:38 am
Can someone explain what methods are called when an object is used as an index? Or is it simply that it type-checks the object to make sure its an integer and then just gets the value?
I'm fairly sure this is exactly right (from a quick look at list subscr in objlist.c and mp_get_index in obj.c).

MicroP_W691
Posts: 10
Joined: Mon Mar 09, 2020 10:47 am

Re: Equivalent __index__ method in Micropython

Post by MicroP_W691 » Tue Apr 28, 2020 3:37 pm

Ah ok, not a problem, thanks for the info @jimmo

Post Reply