0

I wrote this code and received an unexpected output than I thought.

def egg():
    print(a)

egg() # NameError: name 'a' is not defined **As excepted**

egg.a = 50

egg() # NameError: name 'a' is not defined **Not as excepted**

My hope was that after setting agg.a = 50 the next time I would call agg() a variable will be defined.

Can someone please explain what am I missing? why a is not added to the function scope dynamically

p.s. when I used dir(egg) I could see a was add the the function dict

5
  • To put it simply: you can't and neither you should. If you want modifiable variable make it a parameter. Or create a class with this as an attribute. Commented Nov 10, 2022 at 13:24
  • I now understand I can't, however, my question is why? Commented Nov 10, 2022 at 13:28
  • Because it breaks function encapsulation. If inner variables were modifiable from outside the function, such code would be very hard to follow and debug. Commented Nov 10, 2022 at 13:30
  • Function attributes have nothing to do with the names visible to the function body. Commented Nov 10, 2022 at 13:30
  • lol, when you do "egg.a" "a" is in the namepspace of "egg" not in the local namespace of code execution that is generated when the function runs statements by statements Commented Nov 10, 2022 at 13:39

2 Answers 2

1

uisng non local params

def main():
    def egg():
        nonlocal a
        print(a)

    #egg() # NameError: name 'a' is not defined **As excepted**

    a = 50

    egg()
main()

output

50
Sign up to request clarification or add additional context in comments.

2 Comments

nonlocal and global variables should be used as rarely as possible.
Agree...Just don't want to chnage the structure of the OP algorithm....Thinking for alternate solution...Meanwhile posted it
0

Callable class can be used to replicate this sort of behaviour without breaking the encapsulation of a function.

class Egg:
    def __init__(self, a):
        self.a = a
    def __call__(self):
        print(self.a)

egg = Egg(50)

egg() # 50

egg.a = 20

egg() # 20

2 Comments

Can you please explain why a is not added to the function scope? Does it mean its a function attribute and not an function variable?
@RaphaelGozlan egg.a would be a function attribute. This is specifically not the same as a variable seen inside that function. I haven't encountered a single good use for such an attribute.

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.