How to identify the method that has called another method ?

John J. Lee jjl at pobox.com
Sat Jul 19 09:42:09 EDT 2003


Michael Hudson <mwh at python.net> writes:

> martin_a_clausen at hotmail.com (Mars) writes:
> 
> > 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 ?
> 
> No.  sys.getframe(1).f_code.co_name might be a start.
> 
> > (and is this a silly idea in general ?)
> 
> I've always disliked trying to disallow this kind of abuse -- it's
> very hard to make it impossible, and I think you're better off just
> documenting the restrictions.
[...]

A hard-to-miss way of documenting it:

class MyClass:
    def __init__(self, arga, argb,
                 yes_I_know_I_should_use_the_factory_function=False):

def Factory():
    return MyClass(get_arga(), get_argb(), True)


John




More information about the Python-list mailing list