annoying behavior

Jeremy Jones zanesdad at bellsouth.net
Tue Sep 28 13:13:59 EDT 2004


Elbert Lev wrote:

># here is the problem I ran into:
>
>class foo:
>    def __init__(self, host):
>        self.f()
>        self.r = True
>    
>    def f(self):
>        if self.r:
>            #<do something>
>            pass
>        else:
>            #<do something else>
>            pass
>
>f = foo("1234")
>
>#here is the output:
>
>#Traceback (most recent call last):
>#  File "G:\MyProjects\Python\Little\inconv.py", line 16, in ?
>#    f = foo("1234")
>#  File "G:\MyProjects\Python\Little\inconv.py", line 5, in __init__
>#    self.f()
>#  File "G:\MyProjects\Python\Little\inconv.py", line 9, in f
>#    if self.r:
>#AttributeError: foo instance has no attribute 'r'
>
># I understand why does this happen, but, to tell the truth,
># this feature is very annoying. 
># Are there any plans to relax this restriction? 
># In 3.0 :)?
>  
>
Relax what restriction?  Why should this behave any differently than it 
is?  I would kind of equate the above code to:

 >>> f = {}
 >>> f['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'a'
 >>> f['a'] = 1


How should Python know that I'm going to assign f['a'] to anything 
before it gets assigned?  That's like expecting this:

 >>> f = {}
 >>> f['a']
 >>> #I'm planning on setting f['a'] to something in a little bit - 
maybe the Python interpreter can figure out what I'm going to do....
1
 >>> f['a'] = 1

to produce the results that I just typed in.  You're calling method f() 
before you are setting attribute r to anything, so when you call f(), 
attribute r isn't set, so you get an exception.  What restriction do you 
want to relax?  Do you want the Python interpreter to read ahead and 
figure out if you were intending to set a variable and then use some 
variable that you were planning on setting in the future?  If so, what 
if you set it and then set it again?  Which one should it choose?

Jeremy



More information about the Python-list mailing list