0

I am trying to understand how python stores and accesses its functions as objects . For example take the following code-

def make_pretty(func):
    def inner():
        print("I got decorated")
        func()
        return func
    return inner

def ordinary():
    print("I am ordinary 2")

ordinary()
pretty=make_pretty(ordinary)

pretty()

When executed , pretty() returns

I got decorated
I am ordinary 2
<function __main__.ordinary()>

which seems to imply that the ordinary() function passed to make_pretty() is accessed as in the main scope, and as dir(pretty) doesn't show ordinary (Please correct me if i am wrong). Now if I run this code after this

def ordinary():
    print("I am ordinary 3")

pretty()

I still get the same output as before , even though I have the changed the global definition of ordinary , i.e. pretty still is considering the previous definition of ordinary even though I have redefined ordinary and the func in pretty is referring to global ordinary

Why is this so? I clearly am wrong somewhere but I don't understand where. Some insight would be appreciated. Thanks

2
  • You should read more about object references in python. Commented Aug 18, 2018 at 19:25
  • I read about object references from python-course.eu/passing_arguments.php , from what I understand in this case , ordinary is called by reference until it is changed , and when it is changed it becomes call by value . is this correct ? Commented Aug 18, 2018 at 19:42

1 Answer 1

1

even though I have the changed the global definition of ordinary , i.e. pretty still is considering the previous definition of ordinary even though I have redefined ordinary and the func in pretty is referring to global ordinary

You didn't change the function object that pretty refers to. You created a new function, and gave the name ordinary to it. The original function still exists, but can no longer be referred to by the name ordinary.

pretty doesn't know about all this. It refers to the original function all the time.

Before

Both the name "ordinary" and the function pretty refer to the same function:

<function 1>  <-- "ordinary"
              <-- pretty

After

The name "ordinary" refers to a new function, but pretty still refers to the original function:

<function 1>  <-- pretty

                "ordinary" -->  <function 2>
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah understood that after using id for the function , thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.