Proposal for adding symbols within Python
Rocco Moretti
roccomoretti at hotpop.com
Tue Nov 15 15:02:47 EST 2005
Björn Lindström wrote:
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
>
>
>>Why does the byte string "\x6f\x70\x65\x6e\x65\x64" have intrinsic
>>meaning when the int 0 doesn't? It certainly doesn't mean anything to
>>non-English speakers.
>>
>>If all you want is human readable byte strings, then just use them:
>>
>>class MyFile:
>> def open(self):
>> self.state = "opened"
>> def close(self):
>> self.state = "closed"
>
>
> So, I guess no one read my explanation of why this an issue about more
> than implementing enums (which is fairly trivial, as we have seen).
I did, but I still don't see why it is an argument against using
strings. The point you may not appreciate is that (C)Python already uses
strings to represent names, as an important part of its introspective
abilities.
##########################################
>>> import dis
>>> def f():
module.klass.method()
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (module)
3 LOAD_ATTR 1 (klass)
6 LOAD_ATTR 2 (method)
9 CALL_FUNCTION 0
12 POP_TOP
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>> f.func_code.co_names
('module', 'klass', 'method')
>>> type(f.func_code.co_names[1]) is type('a')
True
##############################################
I'll let you dig through the interpreter source to convince yourself
that, indeed, the names module, klass, and method are stored internally
as true python strings. The same holds for other namespaces - the names
are stored as real python strings, in a real python dictionary.
############################################
>>> class c:
def foo(self):
pass
def bar(self):
pass
def baz(self):
pass
>>> type(c.__dict__) is type({})
True
>>> c.__dict__.keys()
['baz', '__module__', 'foo', 'bar', '__doc__']
>>> type(c.__dict__.keys()[0]) is type('a')
True
##############################################
P.S. This may change for other implementations of Python, but the fact
remains - there is less difference between names and strings than you
may first think.
More information about the Python-list
mailing list