micropython

docs/getattr.txt

530:0f9aa4c4d92c
2012-06-09 Paul Boddie Added an __iter__ method for strings.
     1 Dynamic Attribute Access
     2 ========================
     3 
     4 Access to attributes using specific names can either be analysed at
     5 compile-time or supported at run-time using the object table. However, access
     6 to arbitrary attributes which are not explicitly identified in the program as
     7 attribute access operations requires additional support. Thus, functions such
     8 as getattr require a means of converting string values to attribute
     9 references.
    10 
    11 Although a dictionary could be used to support dynamic attribute accesses, an
    12 alternative approach involves identifying constant strings which might refer
    13 to active attributes. If getattr is used in a program, such string instances
    14 are extended with an extra attribute containing the object table index which
    15 would yield an attribute in an object table lookup. For example:
    16 
    17   class C:
    18       x = 123
    19 
    20   attrname = "x" # generates constant with attribute giving index of "x"
    21                  # belonging to a special _accessor class
    22 
    23 The _accessor class is a subclass of str:
    24 
    25   class _accessor(str):
    26       pass
    27 
    28 In pseudocode, the constant would be initialised as follows:
    29 
    30   "x" = _accessor(<data for "x">, <index of "x">)
    31 
    32 When used with getattr, an attempt is made to access the special attribute on
    33 the given attribute name string. Such instances are able to provide an index
    34 and this is used in the object table lookup:
    35 
    36   # in the native getattr(obj, attrname) function...
    37   index = attrname._index # this yields the index offset directly
    38 
    39 Where getattr is not in use, no string constants are _accessor instances.
    40 
    41 A significant limitation of this approach is that strings cannot be combined
    42 or modified to create strings which are then used with getattr, nor can
    43 strings be introduced at run-time to access attributes dynamically. However,
    44 since such string manipulation is potentially a source of errors and resists
    45 analysis of program code, a compromise offering basic support for dynamic
    46 access and program inspection is arguably a suitable alternative.