← index #5322PR #6130
Duplicate · high · value 0.513
QUERY · ISSUE

Listing class attributes in the defined order

openby andrewleechopened 2019-11-12updated 2020-06-09
py-core

I've got a config file management package I'm trying to port to micropython, where the config file structure is defined as a python class: https://pypi.org/project/structured-config/

Some of the features of this module are dependent on knowing the order and iterating over of attributes defined in a class.

This kind of ordered attributes access can also be useful for various dataclass type behaviors.

Currently the only way I can find to get attributes listed on a class is with dir()

>>> bar = None
>>> 
>>> class Structure:
>>> 	first = 1
>>> 	foo = 0x0f
>>> 	bar = 0x0b
>>> 	last = 2
>>> 
>>> print(dir(Structure))
['__class__', '__module__', '__name__', '__qualname__', '__bases__', 'bar', 'first', 'foo', 'last']

However, looking at the source for dir(), I can see that that it works by iterating over every QSTR defined in micropython and checks the class/object for each one to see if it exists (seems a bit backwards to me) so they get listed in the order they're (ever) defined in micropython
https://github.com/micropython/micropython/blob/master/py/modbuiltins.c#L175

Is there any other way in micropython currently this could be accomplished?

CANDIDATE · PULL REQUEST

py/modbuiltins: Keep class locals ordered as per their definition.

openby andrewleechopened 2020-06-09updated 2025-11-03
py-core

When MICROPY_PY_CLASS_ORDERED_LOCALS build/board define is set this will keep all class attributes ordered as per their python definition.

As discussed in https://github.com/micropython/micropython/issues/5322#issuecomment-641035846

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied