Python Oddity - print a reserved name

Steve Holden sholden at holdenweb.com
Wed Sep 15 15:11:46 CEST 2004


Michael Foord wrote:

> Here's a little oddity with 'print' being a reserved word...
> 
> 
>>>>class thing:
> 
> 	pass
> 
> 
>>>>something = thing()
>>>>something.print = 3
> 
> SyntaxError: invalid syntax
> 
>>>>print something.__dict__
> 
> {}
> 
>>>>something.__dict__['print'] = 3
>>>>print something.__dict__
> 
> {'print': 3}
> 
>>>>print something.print
> 
> SyntaxError: invalid syntax
> 
>>>> 
> 
> 
> See that I can't set the something.print attribute directly, but can
> set it indirectly. Is this behaviour 'necessary' or just an anomaly of
> the way IDLE detects Syntax Errors ?
> 
It's necessary. You will find that keywords (those having a specific 
meaning as a language token, such as "def" and "print") can't be used as 
attributes. The fact that you can set the attributes by manipulating the 
__dict__ directly isn't relevant - you will find you can only access 
such attributes indirectly, since any attempt to do so directly will 
result in a syntax error no matter how the Python interpreter is invoked.

regards
  Steve



More information about the Python-list mailing list