Skip to content

Instantly share code, notes, and snippets.

@debugger22
Created June 23, 2015 11:14
Show Gist options
  • Save debugger22/6878911fc24130188db4 to your computer and use it in GitHub Desktop.
Save debugger22/6878911fc24130188db4 to your computer and use it in GitHub Desktop.
Modify Symbol to add assumptions to global assumptions
commit de49998cc22c1873799539237d6202134a463956
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 23 16:35:13 2015 +0530
Symbol creation adds provided assumptions to global assumptions
diff --git a/sympy/core/symbol.py b/sympy/core/symbol.py
index 3945fa1..45be26d 100644
--- a/sympy/core/symbol.py
+++ b/sympy/core/symbol.py
@@ -96,8 +96,41 @@ def __new__(cls, name, **assumptions):
False
"""
+ from sympy.assumptions.assume import global_assumptions
+ from sympy.assumptions.ask import Q
+
cls._sanitize(assumptions, cls)
- return Symbol.__xnew_cached_(cls, name, **assumptions)
+ sym = Symbol.__xnew_cached_(cls, name, **assumptions)
+
+ items_to_remove = []
+ # Remove previous assumptions on the symbol with same name.
+ # Note: This doesn't check expressions e.g. Q.real(x) and
+ # Q.positive(x + 1) are not contradicting.
+ for assumption in global_assumptions:
+ if isinstance(assumption.arg, cls):
+ if str(assumption.arg) == name:
+ items_to_remove.append(assumption)
+
+ for item in items_to_remove:
+ global_assumptions.remove(item)
+
+ for key, value in assumptions.items():
+ if not hasattr(Q, key):
+ continue
+ # Special case to handle commutative key as this is true
+ # by default
+ if key == 'commutative':
+ if not assumptions[key]:
+ global_assumptions.add(~getattr(Q, key)(sym))
+ continue
+
+ if value:
+ global_assumptions.add(getattr(Q, key)(sym))
+ elif value is False:
+ global_assumptions.add(~getattr(Q, key)(sym))
+
+ return sym
+
def __new_stage2__(cls, name, **assumptions):
if not isinstance(name, string_types):
Master
In [1]: from sympy import *
In [2]: %time x = Symbol('x', positive=True, real=True, integer=True)
CPU times: user 233 µs, sys: 29 µs, total: 262 µs
Wall time: 231 µs
This branch
In [1]: from sympy import *
In [2]: %time x = Symbol('x', positive=True, real=True, integer=True)
CPU times: user 652 µs, sys: 42 µs, total: 694 µs
Wall time: 657 µs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment