What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource.
Symbols are immutable: Their value remains constant. Multiple uses of the same symbol have the same object ID and are the same object compared to string which will be a different object with unique object ID, everytime.
What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.
The :symbol , is as you mentioned it's an efficient way of representing names and strings; they are literal values. It is initialized and exists only once during the ruby session. It's not a string, since you don't have access to String methods; it's a Symbol. On top of that, it's immutable.
No, python doesn't have a symbol type.
However string literals are interned by default and other strings can be interned using the intern
function. So using string literals as keys in dictionaries is not less performant than using symbols in ruby.
As others have said, there is no symbol in Python, but strings work well.
To avoid quoting strings as keys, use the dict() constructor syntax:
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. For example you could do:
some_var = object()
and then set a dictionary key as 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. 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:
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.
Not as a first-class type but there does exist https://pypi.python.org/pypi/SymbolType.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With