On Fri, May 4, 2012 at 7:22 AM, Tom Evans <[email protected]> wrote:
> On Fri, May 4, 2012 at 4:30 AM, cj <[email protected]> wrote:
>> Hi to all,
>>
>> Just wan't to ask if its possible.
>>
>> at helper.py
>>
>> def myfunc():
>>    blah blah blah
>>
>> and then in views.py
>>
>> def myview1():
>>    myfunc()
>>
>> def myview2():
>>   myfunc()
>>
>> my question is how can i get the caller function from myfunc().
>>
>> i'm a newbie at python django so i hope you can help me.
>>
>> Thanks in advance.
>>
>> Cheers
>>
>
> Not got much to do with django tbh, you will get more complete help on
> an actual python mailing list.
>
> However:
>
>
> import inspect
>
> def stack_inspector():
>    print "In stack_inspector()"
>    stack = inspect.stack()
>    print "Called from %s" % stack[1][3]
>
> def func1():
>    print "In func1()"
>    stack_inspector()
>
>>>> func1()
> In func1()
> In stack_inspector()
> Called from func1
>
> http://docs.python.org/library/inspect.html
>
> Cheers
>
> Tom
>

Another point is that while you *can* do this, the circumstances in
which it is a good way to approach a problem are quite rare.  You
don't describe why you want to do this, so it's hard to comment.

If this is for production code, beware that it will obfuscate the
operation, making life difficult when you (or someone else) comes back
to work on it later.  A better option is to pass an additional
argument, identifying the source.  Or, if you are looking to use code
that you don't want to edit (part of some standard package that you
don't want to customize), which in turn calls your code, then you
could add an attribute to some object you are already passing (in
general python objects are amenable to dynamic attribute creation).
In the case of a view, such an object might be the request.

For debugging, do you know about all the clickable elements in those
fine stactraces that Django prints in debug mode error messages?
(Many folks don't realize that you can click on the code line in order
to see it in context.)  Also, if you stick:
    import pdb;pdb.set_trace()
at the interesting point in your code (not for the faint of heart
under mod_wsgi, but straightforward under the development server), and
then use pdb's u command (also d) to move up (and down) the (root at
the top) stack to inspect local variables.

As a learning experience, fine.  In addition to inspect, see also the
traceback module.

Bill

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to