def __new__(cls, *args): def flatten(arg): if is_flattenable(arg): return sum(map(flatten, arg), []) return [arg] args = flatten(list(args)) # Sympify Arguments args = map(sympify, args) # Turn tuples into Tuples args = [Tuple(*arg) if arg.__class__ is tuple else arg for arg in args] if len(args) == 0: return EmptySet() if all(arg.is_number and arg.is_real for arg in args): cls = RealFiniteSet elements = frozenset(map(sympify, args)) obj = Basic.__new__(cls, elements) obj.elements = elements return obj
def sympify(a, locals=None, convert_xor=True, strict=False, rational=False): """ Converts an arbitrary expression to a type that can be used inside sympy. For example, it will convert python ints into instance of sympy.Rational, floats into instances of sympy.Float, etc. It is also able to coerce symbolic expressions which inherit from Basic. This can be useful in cooperation with SAGE. It currently accepts as arguments: - any object defined in sympy (except matrices [TODO]) - standard numeric python types: int, long, float, Decimal - strings (like "0.09" or "2e-19") - booleans, including ``None`` (will leave them unchanged) - lists, sets or tuples containing any of the above If the argument is already a type that sympy understands, it will do nothing but return that value. This can be used at the beginning of a function to ensure you are working with the correct type. >>> from sympy import sympify >>> sympify(2).is_integer True >>> sympify(2).is_real True >>> sympify(2.0).is_real True >>> sympify("2.0").is_real True >>> sympify("2e-45").is_real True If the expression could not be converted, a SympifyError is raised. >>> sympify("x***2") Traceback (most recent call last): ... SympifyError: SympifyError: "could not parse u'x***2'" If the option ``strict`` is set to ``True``, only the types for which an explicit conversion has been defined are converted. In the other cases, a SympifyError is raised. >>> sympify(True) True >>> sympify(True, strict=True) Traceback (most recent call last): ... SympifyError: SympifyError: True To extend `sympify` to convert custom objects (not derived from `Basic`), the static dictionary `convert` is provided. The custom converters are usually added at import time, and will apply to all objects of the given class or its derived classes. For example, all geometry objects derive from `GeometryEntity` class, and should not be altered by the converter, so we add the following after defining that class: >>> from sympy.core.sympify import converter >>> from sympy.geometry.entity import GeometryEntity >>> converter[GeometryEntity] = lambda x: x """ try: cls = a.__class__ except AttributeError: #a is probably an old-style class object cls = type(a) if cls in sympy_classes: return a if cls in (bool, type(None)): if strict: raise SympifyError(a) else: return a try: return converter[cls](a) except KeyError: for superclass in getmro(cls): try: return converter[superclass](a) except KeyError: continue try: return a._sympy_() except AttributeError: pass if not isinstance(a, basestring): for coerce in (float, int): try: return sympify(coerce(a)) except (TypeError, ValueError, AttributeError, SympifyError): continue if strict: raise SympifyError(a) if isinstance(a, tuple): from containers import Tuple return Tuple(*[sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a]) if iterable(a): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a]) except TypeError: # Not all iterables are rebuildable with their type. pass if isinstance(a, dict): try: return type(a)([sympify(x, locals=locals, convert_xor=convert_xor, rational=rational) for x in a.iteritems()]) except TypeError: # Not all iterables are rebuildable with their type. pass # At this point we were given an arbitrary expression # which does not inherit from Basic and doesn't implement # _sympy_ (which is a canonical and robust way to convert # anything to SymPy expression). # # As a last chance, we try to take "a"'s normal form via unicode() # and try to parse it. If it fails, then we have no luck and # return an exception try: a = unicode(a) except Exception, exc: raise SympifyError(a, exc)