提交 4f1f59ac authored 作者: Olivier Delalleau's avatar Olivier Delalleau

Somewhat elaborated fix to be able to deepcopy functions with Python 2.4 => Fixes a few tests

上级 a92141e7
__authors__ = "Olivier Delalleau"
__contact__ = "delallea@iro"
"""
Utility classes for singletons.
"""
class Singleton(object):
"""Base class for Singletons."""
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
return cls._instance
class DeepCopiableFunction(Singleton):
"""
Utility class to work around Python 2.4 limitations.
The problem is that trying to deep copy a function in Python 2.4 raises
an exception. In Python 2.5+, deepcopying a function simply returns the
same function (there is no actual copy being performed).
Instances of subclasses are like "deepcopy-able functions": they are
callable singleton objects.
For instance if you plan to deepcopy a function f, instead of:
def f():
return 0
write instead:
class F(DeepCopiableFunction):
def __call__(self):
return 0
f = F()
"""
def __deepcopy__(self, memo):
# Simply return a pointer to self (same as in Python 2.5+).
return self
def __eq__(self, other):
if type(self) != type(other):
return False
# Since it is a singleton there should be no two different instance
# of this class.
assert self is other
return True
def __hash__(self):
# Required for Ops that contain such functions.
return hash(type(self))
......@@ -22,6 +22,7 @@ from theano import gof
from theano.gof import Op, utils, Variable, Constant, Type, Apply, Env
from theano.gof.python25 import partial, all, any
from theano.configparser import config
from theano.misc.singleton import DeepCopiableFunction
builtin_complex = complex
builtin_int = int
......@@ -492,10 +493,17 @@ complexs64 = _multi(complex64)
complexs128 = _multi(complex128)
# Note that currently only upcast_out inherits from DeepCopiableFunction,
# because it is enough to make the test-suite pass with Python 2.4. However,
# it may prove necessary to use this same mechanism in other places as well
# in the future.
# Note that turning a function into an instance of a DeepCopiableFunction
# subclass is backward compatible w.r.t. old pickled files.
class UpcastOut(DeepCopiableFunction):
def __call__(self, *types):
return Scalar(dtype = Scalar.upcast(*types)),
upcast_out = UpcastOut()
def upcast_out(*types):
return Scalar(dtype = Scalar.upcast(*types)),
def upcast_out_no_complex(*types):
if any([type in complex_types for type in types]):
raise TypeError('complex type are not supported')
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论