如何在Python中为变量分配内存地址?

时间:2021-10-08 23:07:31

here's the scenario:

这是场景:

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

我愚蠢地忘记将返回的对象分配给变量:

>>> open("random_file.txt")
<open file 'random_file.txt', mode 'r' at 0x158f780>

Is there a way to directly assign the memory address to a variable? Something roughly equivalent to

有没有办法直接将内存地址分配给变量?大致相当于的东西

int *ptr;
*ptr = 0x158f780;

Counter-points:

  1. In this case I can just discard the object - the file's opened in read mode and the object will be collected by the GC. But I'm interested in a solution for the scenario where I need to free the resource in a deterministic way.

    在这种情况下,我可以丢弃该对象 - 文件以读取模式打开,该对象将由GC收集。但是我对于需要以确定性方式释放资源的场景的解决方案感兴趣。

  2. I assume that the "at 0x158f780" part is just the id() of the object - which happens to be the memory address in CPython ("this is implementation-specific and may change, blah-blah"). So I'm interested in both scenarios - binding a variable to the id() value would be great (more portable and what not), but binding it to a bare memory address would also be O.K.

    我假设“at 0x158f780”部分只是对象的id() - 恰好是CPython中的内存地址(“这是特定于实现的,可能会改变,等等”)。所以我对这两种情况都很感兴趣 - 将变量绑定到id()值会很好(更可移植,什么不可以),但是将它绑定到裸存储器地址也是O.K.

  3. I did google around a bit for anything "python pointer"-related, variable/memory address assignment and similar, but it seems my google-fu is not strong enough.

    我做了一些谷歌左右任何“python指针”相关,变量/内存地址分配和类似,但似乎我的谷歌fu不够强大。

Cheers,

EDIT:

Some tangents after reading the answers and browsing the python docs: the file object is referenced by the REPL _ var. As soon as _ is assigned to the result of the next command, I assume its refcount goes to 0. The file object is removed from memory, and if we assume it implements a sane __del__ method, it should take care of all the low-level details, i.e. closing the file and so on. http://docs.python.org/reference/datamodel.html#object.__del__ details the general scenario.

阅读答案并浏览python文档后的一些切线:文件对象由REPL _ var引用。一旦_被分配给下一个命令的结果,我认为它的引用计数变为0.文件对象从内存中删除,如果我们假设它实现了一个理智的__del__方法,它应该处理所有的低 - 级别详细信息,即关闭文件等。 http://docs.python.org/reference/datamodel.html#object.__del__详细介绍了一般情况。

That and I'll be adding 0.0.0.0 *.com to /etc/hosts...

那我和我将把0.0.0.0 *.com添加到/ etc / hosts ...

2 个解决方案

#1


14  

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

Python是一种高级语言。你不能(不是直接)乱用内存地址所以答案是否定的。

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.

然而,REPL可以方便地将最后一个表达式的结果存储在一个魔术变量_中。你可以从那里获取它。引用你的例子。

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

#2


3  

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.

当其他人有状态时,打印的最后一个对象由REPL存储在_中,因此如果它在交互式会话期间发生并且您很快就能捕获它,则可以使用它。

(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.)

(请注意,严格来说,您可以编写一个CPython扩展,它提供一个函数来获取Python int,获取原始未装箱的值并将其转换为PyObject *。这两者都非常糟糕且不切实际。)

#1


14  

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

Python是一种高级语言。你不能(不是直接)乱用内存地址所以答案是否定的。

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.

然而,REPL可以方便地将最后一个表达式的结果存储在一个魔术变量_中。你可以从那里获取它。引用你的例子。

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

#2


3  

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.

当其他人有状态时,打印的最后一个对象由REPL存储在_中,因此如果它在交互式会话期间发生并且您很快就能捕获它,则可以使用它。

(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.)

(请注意,严格来说,您可以编写一个CPython扩展,它提供一个函数来获取Python int,获取原始未装箱的值并将其转换为PyObject *。这两者都非常糟糕且不切实际。)