1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/docs/getattr.txt Mon Feb 06 19:06:46 2012 +0100
1.3 @@ -0,0 +1,46 @@
1.4 +Dynamic Attribute Access
1.5 +========================
1.6 +
1.7 +Access to attributes using specific names can either be analysed at
1.8 +compile-time or supported at run-time using the object table. However, access
1.9 +to arbitrary attributes which are not explicitly identified in the program as
1.10 +attribute access operations requires additional support. Thus, functions such
1.11 +as getattr require a means of converting string values to attribute
1.12 +references.
1.13 +
1.14 +Although a dictionary could be used to support dynamic attribute accesses, an
1.15 +alternative approach involves identifying constant strings which might refer
1.16 +to active attributes. If getattr is used in a program, such string instances
1.17 +are extended with an extra attribute containing the object table index which
1.18 +would yield an attribute in an object table lookup. For example:
1.19 +
1.20 + class C:
1.21 + x = 123
1.22 +
1.23 + attrname = "x" # generates constant with attribute giving index of "x"
1.24 + # belonging to a special _accessor class
1.25 +
1.26 +The _accessor class is a subclass of str:
1.27 +
1.28 + class _accessor(str):
1.29 + pass
1.30 +
1.31 +In pseudocode, the constant would be initialised as follows:
1.32 +
1.33 + "x" = _accessor(<data for "x">, <index of "x">)
1.34 +
1.35 +When used with getattr, an attempt is made to access the special attribute on
1.36 +the given attribute name string. Such instances are able to provide an index
1.37 +and this is used in the object table lookup:
1.38 +
1.39 + # in the native getattr(obj, attrname) function...
1.40 + index = attrname._index # this yields the index offset directly
1.41 +
1.42 +Where getattr is not in use, no string constants are _accessor instances.
1.43 +
1.44 +A significant limitation of this approach is that strings cannot be combined
1.45 +or modified to create strings which are then used with getattr, nor can
1.46 +strings be introduced at run-time to access attributes dynamically. However,
1.47 +since such string manipulation is potentially a source of errors and resists
1.48 +analysis of program code, a compromise offering basic support for dynamic
1.49 +access and program inspection is arguably a suitable alternative.