Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Created April 18, 2016 19:26
Show Gist options
  • Select an option

  • Save dansondergaard/107fb2bfe3a1bdbbf963c6348cc9f536 to your computer and use it in GitHub Desktop.

Select an option

Save dansondergaard/107fb2bfe3a1bdbbf963c6348cc9f536 to your computer and use it in GitHub Desktop.
Implementation of a symbol type in Python.
#!/usr/bin/env python
import unittest
class symbol(object):
CACHE = {}
def __new__(cls, name):
if not isinstance(name, basestring):
raise TypeError('argument `name` must be a string')
if name not in symbol.CACHE:
symbol.CACHE[name] = super(cls, symbol).__new__(cls, name)
return symbol.CACHE[name]
def __init__(self, name):
self.name = name
class SymbolTest(unittest.TestCase):
def test_create_symbol_not_equal(self):
self.assertNotEqual(symbol('foo'), symbol('bar'))
def test_create_symbol_equal(self):
self.assertEqual(symbol('foo'), symbol('foo'))
def test_create_symbol_with_number_name_raises_exception(self):
with self.assertRaises(TypeError):
symbol(42)
def test_create_symbol_with_dict_name_raises_exception(self):
with self.assertRaises(TypeError):
symbol({'foo': 'bar'})
def test_create_symbol_with_list_name_raises_exception(self):
with self.assertRaises(TypeError):
symbol(['foo', 'bar'])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment