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:
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.
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.
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.
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.
That and I'll be adding 0.0.0.0 stackoverflow.com to /etc/hosts...