Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning variables inside a function: Strange behaviour

Tags:

python

I use Python rarely, so it's unclear to me why such behaviour is allowed: There is no w object and hence it has no s attribute, then why f allows to make w.s assignment?

>>> def f():
    w.s="ads"  #allows, no exception
>>> w.s="sds"  #outside function
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    w.s="sds"
NameError: name 'w' is not defined
like image 853
parsecer Avatar asked Feb 17 '26 14:02

parsecer


1 Answers

Try running your function and see what happens. Python doesn't catch it as you write your code but as soon as you run the code it will error.

What you see is because python doesn't know that by the time your function runs there won't be an object w with an attribute s. However, when you do it outside the function call it checks that there is no w in the scope and thus errors.

Try this:

def f():
    w.s = "one"
w.s  = "one" # called before there is such an object
f() # called before w exists, it will error out    

class SomeClass(object):
    def __init__(self):
        self.s = "two"

w = SomeClass()
f() # since w exists it will run
like image 61
limbo Avatar answered Feb 19 '26 04:02

limbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!