Can you use self in __str__

Chris Angelico rosuav at gmail.com
Sat Nov 29 04:36:47 CET 2014


On Sat, Nov 29, 2014 at 2:16 PM, Shiyao Ma <i at introo.me> wrote:
> 2014-11-28 13:00 GMT+08:00 Chris Angelico <rosuav at gmail.com>:
>> On Fri, Nov 28, 2014 at 2:04 PM, Shiyao Ma <i at introo.me> wrote:
>>> What if it's in the local namespace of a function or method? IDK, try
>>> to get that thing first.
>>
> Sure enough. I will even avoid using "id" as it's dependent on CPython
> implementation. :)

You can use id() on any object. You are guaranteed to get back an
integer which is both stable and unique among all ids of objects that
exist at the same time as the one you called it on. For as long as the
object continues to exist, that number *will* stay the same. Sometimes
that's all you need; for instance, imagine a simple mail server which
produces logs like this:

[142857] Beginning processing of message
[142857] Parsing headers
[314159] Beginning processing of message
[314159] Parsing headers
[142857] Storing in destination mailbox
[314159] Connecting to destination server
[142857] Finished processing of message
[314159] Message accepted by destination
[271871] Beginning processing of message
[314159] Finished processing of message

You can easily see, from the initial numbers, what log lines are
associated with what messages. (Note that emails have their own IDs,
which could in theory be used, but the id() of an internal dict can be
used even before the email's ID has been read - as you see from the
example, a log entry for "Parsing headers" has to be made prior to
info from the headers being used.) It's not a problem if another
142857 comes up later on; there's a very clear begin and end to the
message, and you're guaranteed that nothing can possibly be
interspersed with a colliding ID.

In other implementations of Python, these numbers might look less
arbitrary (Jython, I believe, allocates them sequentially); but the
code will work just as well on any compliant implementation of the
language, because everything I've said above is a language guarantee,
not a CPython implementation detail.

ChrisA



More information about the Python-list mailing list