How to assign a memory address to a variable in Python?

前端 未结 2 737
暖寄归人
暖寄归人 2020-12-16 06:30

here\'s the scenario:

I foolishly forget to assign the returned object to a variable:

>>> open(\"random_file.txt\")


        
相关标签:
2条回答
  • 2020-12-16 06:42

    You can't, for the same reason you can't allocate and free memory yourself and can't cast (as in "let's reinterpret this chunk of memory as if it looked like this") things: Dealing with memory on this level is deemed to error-prone, unimportant and automatable to be included in the language. Be glad it's that way, you propably would have eperienced a few crashes and subtle bugs by now caused by fools who though they'd be clever and abuse something along these lines.

    As others have states, the last object printed is stored in _ by the REPL, so you can use that if it happens during an interactive session and you catch it soon enough.

    (Note that strictly speaking, you could write a CPython extension that provides a function to take a Python int, take raw unboxed value and cast it to a PyObject *. Both awful and impractical.)

    0 讨论(0)
  • 2020-12-16 06:49

    Python is a high level language. You can't (not directly anyway) mess with memory addresses so the answer is no.

    The REPL however does conveniently store the result of the last expression in a magic variable _. You can fetch it from there. To quote your example.

    >>> open("/etc/passwd","r") #Oops I forgot to assign it
    <open file '/etc/passwd', mode 'r' at 0x7f12c58fbdb0>
    >>> f = _ # Not to worry. It's stored as _
    >>> f
    <open file '/etc/passwd', mode 'r' at 0x7f12c58fbdb0>
    >>> 
    
    0 讨论(0)
提交回复
热议问题