简体   繁体   English

是否有Python等效的Ruby符号?

[英]Is there a Python equivalent to Ruby symbols?

Is there a Python equivalent to Ruby symbols? 是否有Python等效的Ruby符号?

  • If so then what is it? 如果是的话那么它是什么?

  • If not then are we stuck with using strings as our keys in dictionaries only? 如果没有,那么我们是不是只使用字符串作为字典中的

No, python doesn't have a symbol type. 不,python没有符号类型。

However string literals are interned by default and other strings can be interned using the intern function. 但是,默认情况下会对字符串文字进行实习,而使用intern函数可以实现其他字符串的实现。 So using string literals as keys in dictionaries is not less performant than using symbols in ruby. 因此,使用字符串文字作为字典中的键并不比使用ruby中的符号具有更高的性能。

As others have said, there is no symbol in Python, but strings work well. 正如其他人所说,Python中没有符号,但字符串运行良好。

To avoid quoting strings as keys, use the dict() constructor syntax: 要避免将字符串作为键引用,请使用dict()构造函数语法:

d = dict(
    a = 1,
    b = 2,
    c = "Hello there",
    )

Also for those interested: symbols in Ruby when used in a hash are very similar to empty objects in python. 对于那些感兴趣的人:在哈希中使用Ruby时的符号与python中的空对象非常相似。 For example you could do: 例如,您可以这样做:

some_var = object()

and then set a dictionary key as some_var: 然后将字典键设置为some_var:

some_dict = { some_var : 'some value' }

and then do a standard retrieval: 然后进行标准检索:

some_dict[some_var]

However, as sepp2k noted there is no performance benefit in doing this. 但是,正如sepp2k所指出的那样,这样做没有性能优势。 In fact I did a quick test and noted little to no performance boost: 事实上,我做了一个快速测试,并注意到几乎没有性能提升:

a, b, c, d, e = [object() for _ in range(5)]
dict_symbols = {a : 'a', b : 'b', c : 'c', d : 'd', e : 'e'}
dict_strings = {'a' : 'a', 'b' : 'b', 'c' : 'c', 'd' : 'd', 'e' : 'e'}

def run_symbols():
    for key in dict_symbols.keys():
        dict_symbols[key]

def run_strings():
    for key in dict_strings.keys():
        dict_strings[key]

Speed tested in ipython: 在ipython中测试速度:

In [3]: %timeit run_symbols
10000000 loops, best of 3: 33.2 ns per loop

In [4]: %timeit run_strings
10000000 loops, best of 3: 28.3 ns per loop

So in my case the 'symbols' run slower! 所以在我的情况下,'符号'运行得更慢! (for fun numbers, not accurate). (对于有趣的数字,不准确)。 However it is to note that there are probably memory advantages to doing it this way. 但是要注意,这样做可能有记忆优势。 If you don't care about the key type objects have a smaller footprint than strings. 如果您不关心键类型对象的占用空间小于字符串。

import sys
sys.getsizeof('some_var') # 45
some_var = object() 
sys.getsizeof(some_var) # 0

Although that raises the question of how python treats the memory of the variable name some_var. 虽然这引发了python如何处理变量名some_var的内存的问题。

  1. No, there is no equivalent. 不,没有相应的。
  2. No you can use every hashable object as dictionary key. 不,您可以将每个可清除对象用作字典键。

不是一流的类型,但确实存在https://pypi.python.org/pypi/SymbolType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM