Update sp.py

some refactoring