program varsum
    version 16.0
    syntax varname [if] [in]
    
	// mark the subsample that satisfies the 
	// if and in qualifiers.
    marksample touse
	
	// pass the variable on which the calculation was to be made 
	// and the variable that identified the subsample
    python: calcsum("`varlist'", "`touse'")
	
    display as txt " sum of `varlist': " as res r(sum)
end

python:
from sfi import Data, Scalar
def calcsum(varname, touse):
    # receive the data from Stata
    x = Data.get(varname, None, touse)

    # calculate the cumulative sum and store 
    # the result into Stata
    Scalar.setValue("r(sum)", sum(x))
end