4

I have overriden the underscore variable _ in the Python interactive interpreter. How can I make the underscore work again without restarting the interpreter?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Vi Ki
  • 119
  • 10
  • 1
    `_` is just a throwaway variable or placeholder. Its value will be overwritten as you continue to use it. – MattDMo Dec 27 '21 at 03:29
  • 1
    @MattDMo I would've thought the same thing, but I just tried it in an interpreter and it very much does not rewrite once shadowed. wjandrea's answer is correct. – Silvio Mayolo Dec 27 '21 at 03:37
  • @MattDMo In this context, it's actually "the result of the last evaluation" and it's exposed by the interactive interpreter as a builtin. I wrote an answer with the solution. – wjandrea Dec 27 '21 at 03:39
  • Related (more broad): [Is the single underscore "_" a built-in variable in Python?](https://stackoverflow.com/q/1538832/4518341) – wjandrea Dec 27 '21 at 03:58

1 Answers1

6
del _

A global _ shadows the builtin _, so deleting the global reveals the builtin again.


It's also worth noting that it doesn't actually stop working, it's just not accessible. You can import builtins to access it:

>>> _ = 'foobar'
>>> 22
22
>>> _
'foobar'
>>> import builtins
>>> 23
23
>>> builtins._
23
wjandrea
  • 28,235
  • 9
  • 60
  • 81