How to Catch When except Secretly Deletes Your Variable
Python deletes the exception variable when the except block ends. Reference it after and get NameError.
#python #except #variabledeletion #nameerror #scope #howto #mindbreaking #gotcha

How to Catch When except Secretly Deletes Your Variable
Python deletes the exception variable when the except block ends. Reference it after and get NameError.
#python #except #variabledeletion #nameerror #scope #howto #mindbreaking #gotcha

#RubyLang #WTF question. Instance vars are #autovivified as `nil`, but locals must be defined to avoid raising #NameError. This works unless you assign the same #lvar on the RHS.
```ruby
a
#=> undefined local variable or method `a' for main (NameError)
a = a
#=> nil
a
#=> nil
defined?(a) == "local-variable"
#=> true
a = b
#=> undefined local variable or method `b' for main (NameError)
@c
#=> nil
```
Why special rules for undefined RHS lvars, but only for self-assignment? Bug or use case?
@onghu This probably won't do what you expect. If name is undefined you will raise #NameError. If name is empty but not nil you will have problems. With #Rails, `format "Hello%s!\n", (defined?(name) && !(name.blank?)) ? (", %s" % name) : "")` would be a cleaner & more flexible.
For clarity, break it into two lines: one to format a string, and one to assign/print it. Readability trumps clever one-liners when you have to read your own code six months later. Future-you will be grateful!