Q: When and why to use dynamic variables?

John Max Skaller skaller at maxtal.com.au
Tue Aug 10 18:37:58 EDT 1999


On Mon, 09 Aug 1999 15:36:53 +0200, Robb Shecter <shecter at darmstadt.gmd.de> wrote:

>Hi,
>
>I'm looking for more information about the ability in Python to add
>variables to an object instance at runtime.  I'm interested in both
>the theoretical as well as practical implications of this feature.
>
>Can anyone point me to information about it?  For example, code where
>this feature is used, descriptions of it, suggested uses, etc.

	Actually, you have it backwards: Python cannot do
anything else. New class instances never have _any_ attributes,
nor do new modules. They have to be added dynamically,
in the class case by executing the __init__ routine,
or in the module case by executing the module.

	So the reverse question is much more important:
how can we compile optimised code if everything is so dynamic?

	There is an answer for functions, that many of the variables
are known, and the compiler generates special instructions referring
to them by number, and storing them in an array.

	The 'theoretical' implications of dynamic attributes
are that optimisation and reasoning about your code is
not easy.

	Here is a 'practical' use of the feature.
I have a program called interscript that weaves special
files into documents. It can weave TeX, HTML, plain
text, and other formats from the same sources.
These weavers are represented by classes
for each kind of document format.

	Now, sometimes, one needs to provide
different data to different kinds of weaver,
but the control program only knows the _abstract_
nature of a weaver. So it makes sense to pass
a whole set of 'arbitrary' attributes to weavers,
and each weaver can use the data if it applies,
or ignore it otherwise.

	Similarly, in order to allow clients
to provide arbitrary arguments on the command
line, which can be accessed inside a document,
I can just use dynamic attributes.

	In both these cases I'm implementing
a kind of 'miniinterpreter' in which I leverage
Pythons own interpreter to do most of the work.
Indeed, interscript's 'mini' interpreter is
full blown python plus more.

	Here's some code:

	# file x.py
	import sys
	def p(x): print x
	exec sys.argv[1]

now,

	python x.py "x=1; y=2; p(x+y)"

which demonstrates the idea.

John Max Skaller                ph:61-2-96600850              
mailto:skaller at maxtal.com.au       10/1 Toxteth Rd 
http://www.maxtal.com.au/~skaller  Glebe 2037 NSW AUSTRALIA




More information about the Python-list mailing list