How to understand '_' in these tests?

classic Classic list List threaded Threaded
3 messages Options
fl
Reply | Threaded
Open this post in threaded view
|

How to understand '_' in these tests?

fl
Hi,

I just know that '_' is the last result in the Python interpreter. I feel that
it is like 'ans' in Matlab. When I run the following commands. The result of
'_' are always '4'.


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'
>>>

Reply | Threaded
Open this post in threaded view
|

How to understand '_' in these tests?

random832@fastmail.us
On Tue, Jun 2, 2015, at 00:18, fl wrote:

> Hi,
>
> I just know that '_' is the last result in the Python interpreter. I feel that
> it is like 'ans' in Matlab. When I run the following commands. The result of
> '_' are always '4'.
>
>
> Because I have tried several commands, such as reversed('fred'), xx and rx,
>  '4' are always there.
>
> What is your explanation about the following?

The use of _ for the last result is a special feature of the REPL. It
does not work if there is a real variable called _.

Try del _ before trying to print _.

Reply | Threaded
Open this post in threaded view
|

How to understand '_' in these tests?

Chris Angelico
In reply to this post by fl
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