dchrostowski / investopedia_simulator_api

A simple Python API for Investopedia's stock simulator games. This programmatically logs into Investopedia and can retrieve portfolio summary, get stock quotes & option chain lookups, execute trades - buy & sell shares, puts, calls, sell short, etc.
MIT License
33 stars 12 forks source link

Method decorator to coerce #6

Closed dchrostowski closed 5 years ago

dchrostowski commented 5 years ago
def conform_value(value,new_type):
    print("converting %s to %s" % (value,new_type))
    if new_type not in (str,Decimal,int):
        return value

    value = re.sub('\s+',' ', str(value)).strip()
    if new_type == str:
        return value

    if new_type == str:
        return value

    if new_type == Decimal:
        return Decimal(re.sub(r'[^\d\.]+','',value))

    elif new_type == int:
        return int(value)

def correct_method_params(func):
    @wraps(func)
    def wrapper(self,*args,**kwargs):
        copy_kwargs = copy.deepcopy(kwargs)
        copy_kwargs.update(dict(zip(func.__code__.co_varnames[1:], args)))
        func_annotations = inspect.getfullargspec(func).annotations
        try:
            new_kwargs = {k:conform_value(copy_kwargs[k], func_annotations[k]) for k in copy_kwargs}
        except KeyError as e:
            warnings.warn("Missing annotations for param(s).  Not correcting any param types for method %s" % func.__qualname__)
            return func(self,*args,**kwargs)
        return func(self,**new_kwargs)
    return wrapper