MCPcopy Create free account
hub / github.com/dblalock/bolt / make_immutable

Function make_immutable

experiments/python/pyience.py:68–98  ·  view source on GitHub ↗

>>> make_immutable(5) == 5 True >>> make_immutable('a') == 'a' True >>> make_immutable((1, 2)) == (1, 2) True >>> make_immutable([1, 2]) == [1, 2] False

(x)

Source from the content-addressed store, hash-verified

66# ------------------------------------------------ misc utils
67
68def make_immutable(x):
69 """
70 >>> make_immutable(5) == 5
71 True
72 >>> make_immutable('a') == 'a'
73 True
74 >>> make_immutable((1, 2)) == (1, 2)
75 True
76 >>> make_immutable([1, 2]) == [1, 2]
77 False
78 """
79 # must either be not a collections or immutable
80 try:
81 {}[x] = 0 # dicts require immutability
82 return x
83 except TypeError:
84 # so it's mutable; either a collection or a
85 # mutable class; if a class, we're hosed, so
86 # assume it's a collection
87 try:
88 # if it's a singleton collection, try returning
89 # first element; this will jump to except
90 # unless x is a collection
91 if len(x) == 1:
92 return make_immutable(x[0])
93
94 # not a singleton collection, but still a collection,
95 # so make it a tuple
96 return tuple(x)
97 except TypeError:
98 return x # not a collection
99
100
101def as_key(x):

Callers 1

as_keyFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected