How can a function find the function that called it?

ChasBrown cbrown at cbrownsystems.com
Fri Dec 24 13:23:59 EST 2010


On Dec 24, 8:24 am, kj <no.em... at please.post> wrote:
> I want to implement a frozen and ordered dict.
>
> I thought I'd implement it as a subclass of collections.OrderedDict
> that prohibits all modifications to the dictionary after it has
> been initialized.
>
> In particular, calling this frozen subclass's update method should,
> in general, trigger an exception ("object is not mutable").
>
> But OrderedDict's functionality *requires* that its __init__ be
> run, and this __init__, in turn, does part of its initialization
> by calling the update method.
>

Rather than trying to identify the caller, I'd do something like:

class FrozenODict(OrderedDict):

    def __init__(self, *args, **kwargs):
        OrderedDict.__init__(self, *args, **kwargs)
        self.update = self._update # init is complete, so override
                                   # update method for this instance

    def _update(self, dict2):
        raise Exception("object is immutable!!")

After the __init__, calls to the instance's 'update' function will be
mapped to _update. It's essentially overriding the inherited function
on the fly.

Cheers - Chas




More information about the Python-list mailing list