[Tutor] Function assignment (was: Re: Function type?)

Zak Arntson zak@harlekin-maus.com
Tue Jun 10 16:58:01 2003


>>
>> But what's the shortcut keyword for a function type? Right now, I have
>> to use a dummy function:
>>
>> Is there a keyword I'm being oblivious to? Or do I need to resort to
>> this dummy function thing?

> You need callable().
>
> Abel Daniel

Thanks, everyone! I think callable() is the way to go. Silly me, not
thinking to look in the built-in functions. I'm working on an interactive
fiction system, and I'm wondering how to best handle things that are
either strings or functions. For example, if you have a item with a
description, you could either have:

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> pipe.desc = "A heavy green pipe."

OR

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> def pipeDesc ():
        if self.parent == player:
             return "A green pipe, heavy in your hands."
        return "A green pipe on the ground."
>>> pipe.desc = pipeDesc

That way the examine code could look like:

def get(obj):
    if callable(obj):
        return obj()
    return obj

class Item:
    ...
    def examine():
       print get(self.desc)

Which leads me to another question: Is it possible to define a function
immediately as a variable? Something like:

>>> pipe = Item('pipe', name='pipe', adj=['green', 'heavy'])
>>> def pipe.desc ():
        if self.parent == player:
            ....

OR

>>> pipe.desc = def ():
        if self.parent == player:
            ....

Or is there a cleaner way to do this that I'm not aware of?

-- 
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em