1

I was studying about inner functions. One of its uses is in closure and factory functions.

Consider the following example I found here

def generate_power(number):
    """
    Examples of use:

    >>> raise_two = generate_power(2)
    >>> raise_three = generate_power(3)
    >>> print(raise_two(7))
    128
    >>> print(raise_three(5))
    243
    """

    # define the inner function ...
    def nth_power(power):
        return number ** power
    # ... which is returned by the factory function

    return nth_power

If I were to run the use case from this example, it would create a new function raise_two.

Can we print function definition of raise_two? (making it easier to understand the whole concept)

edit:

This question requires an answer that is different from the ones found at How can I get the source code of a Python function? as I've explained in the comment section.

Community
  • 1
  • 1
sharhp
  • 359
  • 3
  • 10
  • Based on [this question](http://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function), it would seem that getting the code of a function that is not explicitly defined in a file is not possible. – Random Davis Apr 19 '17 at 17:43
  • Can you be a little more clear? For example, if we had the magic function: `print_func_def(raise_two)`, what output would you expect? – mgilson Apr 19 '17 at 17:44
  • `print(raise_two)` tells you `.nth_power at 0x7f3331141c80>`. `print(raise_two.__closure__)` tells you `(,)`. Is that sufficient? – tdelaney Apr 19 '17 at 17:48
  • Note that the function definition is not going to say `raise_two` or `2` anywhere in it. It'll just be the text of the `nth_power` definition. Closure variables are not substituted into the inner function at inner function definition time. – user2357112 Apr 19 '17 at 17:57
  • @RandomDavis There are some solutions provided in that answer. I didn't find my particular case solved though. – sharhp Apr 19 '17 at 21:14
  • @mgilson May be something like nth_power(power):\nreturn 2 ** power. – sharhp Apr 19 '17 at 21:22
  • @user2357112 Yes, I understand that raise_two will have its name replaced by nth_power, but wouldn't the definition of raise_two be something as above (with the 2?) I had gone through the answers to the claimed duplicate question earlier - I don't want the format in which 'dis' presents the definition & 'dill' doesn't seem to be working for me, so I posted this question. – sharhp Apr 19 '17 at 21:23

0 Answers0