[Python-ideas] Standard way to get caller name and easy call stack access

Barry Warsaw barry at python.org
Tue Mar 27 22:29:08 CEST 2012


On Mar 22, 2012, at 12:17 AM, Sven Marnach wrote:

>(And there is another way -- at least in CPython you can use
>'sys._getframe().f_back.f_code.co_name'.)

Note that back in the day, the motivating factor for sys._getframe() was an
observation I made about internationalizing Python programs.  This boils down
to a DRY argument.  For example, you could do this:

def here_kitty(person, pet):
    print(_('$person has a $pet').safe_substitute(person=person, pet=pet))

So much error-prone DRY.  With sys._getframe(), a package like flufl.i18n can
allow you to write this like so:

def here_kitty(person, pet):
    print(_('$person has a $pet'))

because _() can walk up to the caller's frame and pull out the required
variables.  Now imagine writing hundreds of translatable strings in your
application, which would you prefer?

It would be impossible to port flufl.i18n to implementations that don't
provide an equivalent of sys._getframe(), so it would be nice if there were
perhaps a standard way of spelling this.  OTOH, it was recognized at the time
that this was pretty specialized, and thus it was hidden in an underscore
function.

Cheers,
-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120327/71f65963/attachment.pgp>


More information about the Python-ideas mailing list