How to identify the method that has called another method ?

Bengt Richter bokr at oz.net
Sat Jul 19 12:34:21 EDT 2003


On 18 Jul 2003 07:20:18 -0700, martin_a_clausen at hotmail.com (Mars) wrote:

>Hi.
>
>I am using Python 2.2.3 and new-style classes. I want to implement a
>static factory method to build objects for me. My plan is to have
>__init__ check that it has been called from said factory method and
>not directly. Is there a elegant way of achieving this ? (and is this
>a silly idea in general ?)

You don't say why __init__ should need to check. Are you re-using instances
and only want to do part of the init job if the factory re-uses instances
from a free list?

Why not just leave __init__ out and give your class an ordinary method
for initializing that won't be called except on purpose? And limit __init__
to normal on-creation initialization and don't call it directly. E.g. (untested!)

class MyClass(object):
    def __init__(self):
        self.init_on_creation = 'whatever needs setting once on creation only'
    def myinit(self, whatever):
        self.whatever = whatever # or whatever ;-)

def myfactory(something):
    if freelist: instance = freelist.pop()
    else: instance = MyClass()
    instance.myinit(something)
    return instance
...
directly = MyClass() # no automatic call to directly.myinit
factorymade = myfactory(123)

I'm sure you can think of variations from there.
HTH

Regards,
Bengt Richter




More information about the Python-list mailing list