How to understand '_' in these tests?

Chris Angelico rosuav at gmail.com
Tue Jun 2 01:42:41 EDT 2015


On Tue, Jun 2, 2015 at 2:18 PM, fl <rxjwg98 at gmail.com> wrote:
> Because I have tried several commands, such as reversed('fred'), xx and rx,
>  '4' are always there.
>
> What is your explanation about the following?
>
>
> Thanks,
>
>
>
>
>
>
>>>> reversed('fred')
> <reversed object at 0x02A8DD50>
>>>> _
> '4'
>>>> _
> '4'
>>>> xx
> 33223
>>>> _
> '4'
>>>> rx=reversed('fred')
>>>> _
> '4'
>>>> xx
> 33223
>>>> _
> '4'
>>>>

I think part of what you're seeing as odd here is that when you assign
an expression somewhere, _ doesn't get changed. This is because
there's no final evaluation getting printed out; I suppose it would be
reasonable to unset _ in those cases, but it's more useful to retain
it. The rest is what random832 pointed out, which is that the special
effect of _ can be shadowed just as anything else can. In fact, just
like most things that can be shadowed, it's actually found in the
builtins:

>>> import builtins
>>> 1 + 2
3
>>> builtins._
3

Same goes for other handy names; if you use "dir" to store a directory
name, you can retrieve the original dir() function as "builtins.dir",
or by unsetting your local name with "del dir".

ChrisA



More information about the Python-list mailing list