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

https://www.youtube.com/watch?v=XYOmAQQ336g

How to Catch When except Secretly Deletes Your Variable #howto

YouTube

#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!

#6085 の rake task を production 環境で実行すると #NameError: uninitialized constant ProgressBar が発生する。 ruby-progressbar という gem があるが、 production 環境には存在しない (fuubar という dev/test scope の gem から参照されてる) #bossmemo