Function that knows its argument's variable name

Phlip phlip2005 at gmail.com
Tue Mar 16 19:40:46 EDT 2010


> Yet, the answer to your question is not quite absolutely "no".  Python
> has lots of introspection capabilities, including, perhaps, getting at
> and parsing the original code to find the call.    But there's nothing
> direct for what you want.
>
> Gary Herron

Below my sig is one shot at it; which requires a lambda: for other
reasons. It's an assertion used with Django models.

You can search for the name of your trace method, instead of lambda,
using this brute-force technique.

And here's a nice thread on Greg's technique, from a very short time
ago:

  http://groups.google.com/group/comp.lang.python/msg/03dd85ce009044e9

--
  Phlip
  http://penbird.tumblr.com/

    def assert_model_changes(self, mod, item, frum, too, lamb):
        source = open(lamb.func_code.co_filename, 'r').readlines()
[lamb.func_code.co_firstlineno - 1]
        source = source.replace('lambda:', '').strip()
        model  = str(mod.__class__).replace("'>", '').split('.')[-1]

        should = '%s.%s should equal `%s` before your activation line,
`%s`' % \
                  (model, item, frum, source)

        self.assertEqual(frum, mod.__dict__[item], should)
        lamb()
        mod = mod.__class__.objects.get(pk=mod.pk)

        should = '%s.%s should equal `%s` after your activation line, `
%s`' % \
                  (model, item, too, source)

        self.assertEqual(too, mod.__dict__[item], should)
        return mod



More information about the Python-list mailing list