How to identify the method that has called another method ?

M

Mars

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 ?)

Regards,

Martin
 
M

Michael Hudson

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.

Note that you might want to investigate __new__() by the sounds of
it...

Cheers,
M.
 
B

Bengt Richter

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top