Unique representations of Python objects -
let c python class , assume constructor of c takes integer argument.
consider instructions
x = c(0) y = c(0)
the default behavior of python implies x , y occupy 2 different place in memory.
is possible force x , y share same place in memory?
i happy if python decorator makes job.
[note] looking way memoize constructors (see http://en.wikipedia.org/wiki/memoization memoization of functions).
[add] sage open source mathematics software provides solution problem through class uniquerepresentation
(see here). class should inherit 1 have expected behavior. nevertheless, wondering if there pure python solution problem.
you may want use lru_cache. if class definition is
@lru_cache(maxsize=32) class c(object): def __init__(self, num): self.num = num
then behaves like
>>> = c(1) >>> a.num = 2 >>> b = c(1) >>> b.num 2 >>> b true
however, makes name c
function, , class features aren't usable before class instantiated. if want, can directly cache method __new__
, responsible creation of object. __new__
method takes same arguments __init__
, called before __init__
when create class instances.
as caching output of __new__
straightforward, make things little bit more interesting. let's create new decorator, works lru_cache
, can used classes cache output of __new__
:
def lru_cache_class(maxsize): def wrap(klass): @lru_cache(maxsize=maxsize) def new(cls, *args, **kwargs): self = object.__new__(cls) return self klass.__new__ = new return klass return wrap
we give __new__
possible arguments , keyword arguments can used other classes well. can cache instances of class c2
this:
@lru_cache_class(maxsize=32) class c2(object): def __init__(self, num): self.num = num
and can see objects cached:
>>> c = c2(2) >>> c c2(2) true
there is, however, subtle difference in approach compared first. instance:
>>> d = c2(3) >>> d.num = 4 >>> d.num 4 >>> e = c2(3) >>> d.num == e.num >>> d.num 3
this behavior expected because __init__
called anyway, although object's memory location remains same. depending on use case, may want cache output of __init__
well.
Comments
Post a Comment