Created
April 18, 2016 19:26
-
-
Save dansondergaard/107fb2bfe3a1bdbbf963c6348cc9f536 to your computer and use it in GitHub Desktop.
Implementation of a symbol type in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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