Newbie Python (Game) Programming Question

Peter Hansen peter at engcorp.com
Tue Mar 16 16:02:08 EST 2004


Tina wrote:

> I was wondering if there is a way to insert dynamic program code as data.

Any Python function can be used "as data" the way you are hoping merely 
by using its name.  The result is a "callable" and you can call it at 
any time merely by using parentheses in the normal way.

As a simplified example that should help you along:

> One "what if" is for Myrrhyn women to have +1d6 CHA. Now I could put this in
> the main code but I'm trying to make the basic generator as generic as
> possible for re-use.

import random

def oneDsix():
     '''return 1d6 result'''
     return random.randint(1, 6)

nation = [2, "Melnibone", 3, 1, 10, oneDsix]
CHA_INDEX = 5

chaItem = nation[CHA_INDEX]
if callable(chaItem):
     chaValue = chaItem()
else:
     chaValue = chaItem

# another item might have a non-callable there instead:
nation2 = [1, "Pan Tang", 5, 2, 27, 5]

# in which case chaValue would just equal 5 at the end of the sequence

Somewhat primitive, yes, but you can experiment and expand on the idea 
as needed.

-Peter



More information about the Python-list mailing list