# HG changeset patch # User Paul Boddie # Date 1328551606 -3600 # Node ID c331d79421d33118ab68cfe21af684375f2a7e73 # Parent 06082c8d4e22017f81695843e72fc9a271cdc428 Added getattr notes. diff -r 06082c8d4e22 -r c331d79421d3 docs/getattr.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/docs/getattr.txt Mon Feb 06 19:06:46 2012 +0100 @@ -0,0 +1,46 @@ +Dynamic Attribute Access +======================== + +Access to attributes using specific names can either be analysed at +compile-time or supported at run-time using the object table. However, access +to arbitrary attributes which are not explicitly identified in the program as +attribute access operations requires additional support. Thus, functions such +as getattr require a means of converting string values to attribute +references. + +Although a dictionary could be used to support dynamic attribute accesses, an +alternative approach involves identifying constant strings which might refer +to active attributes. If getattr is used in a program, such string instances +are extended with an extra attribute containing the object table index which +would yield an attribute in an object table lookup. For example: + + class C: + x = 123 + + attrname = "x" # generates constant with attribute giving index of "x" + # belonging to a special _accessor class + +The _accessor class is a subclass of str: + + class _accessor(str): + pass + +In pseudocode, the constant would be initialised as follows: + + "x" = _accessor(, ) + +When used with getattr, an attempt is made to access the special attribute on +the given attribute name string. Such instances are able to provide an index +and this is used in the object table lookup: + + # in the native getattr(obj, attrname) function... + index = attrname._index # this yields the index offset directly + +Where getattr is not in use, no string constants are _accessor instances. + +A significant limitation of this approach is that strings cannot be combined +or modified to create strings which are then used with getattr, nor can +strings be introduced at run-time to access attributes dynamically. However, +since such string manipulation is potentially a source of errors and resists +analysis of program code, a compromise offering basic support for dynamic +access and program inspection is arguably a suitable alternative.