2

For debugging purposes I wanted some lambda functions to be named, i.e. see a __repr__ string. Possible to change a function's repr in python? provides some good answers to how this can be properly done, but I do wonder about the following, "quick and dirty" version (which I won't keep in production code!):

I simply changed the functions' __qualname__. Is that safe to use or do I have to expect some strange side effects - and if so, why? I.e. what other functions might rely on __qualname__?

The code looks somewhat like this:

def make_listener(consumer):
    def listener(obj):
        if _is_doc_of_interest(obj, consumer):
            consumer.put(obj)
    listener.__qualname__ = f'listener({consumer})'
    return listener

And will produce a bunch of functions which will look like:

[make_listener(c) for c in [MyObject(1), SomethingElse(True, 42, 'foo')]

> [
>     <function listener(MyObject(1))>,
>     <function listener(SomethingElse(True, 42, 'foo'))>
>  ]

Again, this is only meant for the purposes of debugging (as I generate a whole lot of listeners and like to identify them quickly), but now I'm curious if this actually produces any side effects or if I can keep using it for quick investigations

Elias Mi
  • 611
  • 6
  • 14
  • 3
    Did you read the PEP that introduced it? https://www.python.org/dev/peps/pep-3155/ – jonrsharpe Jan 18 '18 at 19:32
  • 1
    I don't think it should, but if you want your `lambda` functions to have a name, why not just use a full function definition? – juanpa.arrivillaga Jan 18 '18 at 19:46
  • @jonrsharpe : That reads like there are no side effects to be expected, at least from the python core. – Elias Mi Jan 19 '18 at 20:00
  • @juanpa.arrivillaga : I did the `def` instead of a lambda, but the function is created depending on the consumer which is only available inside the outer def -- and I need the listener function with only one argument. However, in the mean time I found another viable solution: Using `functools.partial`, I pre-occupy the parameter `consumer`. `partial` actually puts a wrapper around the function and has a useful `__repr__` – Elias Mi Jan 19 '18 at 20:03
  • @EliasMi I'm still not sure why a `def` isn't working for you, but I'm glad you found a solution. – juanpa.arrivillaga Jan 19 '18 at 20:05

0 Answers0