Mth Clv Mth Clv - 1 year ago 138
Python Question

Python - Pass a range of float (without step) as an argument of a function

I created a function and I would like to be able to call it with a set of keyworded-parameters that I call


def actionBasedOnParameters(**criterias):
# my code

Inside this set of parameters one of them will be called 'SumInc' and I would like to pass a range to it. The range will be of the form of [1:15] or [1:] or [:15]. Something that will essentially let me check whether a variable in my code is greater than a certain boundary or lower than another boundary or both.
In the same way, as these lines of codes do:

In [188]: 1 <= 15.98877 <= 15
Out[188]: False

In [188]: 1 <= 15.98877
Out[188]: True

In [188]: 15.98877 <= 15
Out[188]: False

But I am looking for a neater way to pass both boundaries without having to create a parameter for each and many if conditions to get things done.

Something that would look like this:

In [189]: criterias = dict(SumInc=[:15])

def actionBasedOnParameters(**criterias):
if criterias['SumInc'] is not None:
if my_variable is in criterias['SumInc']:

Is there something of this kind existing?

Thanks for your tips,

Answer Source

Something like this?

criterias = dict(SumInc=(1,15))

def actionBasedOnParameters(**criterias):
    if 'SumInc' in criterias:
        lower, upper = criterias['SumInc']
        if lower <= my_variable <= upper:

infinity = float('inf')
actionBasedOnParameters(SumInc=(1, 15))
actionBasedOnParameters(SumInc=(-infinity, 15))
actionBasedOnParameters(SumInc=(1, infinity))

Also, you'd better use 'SumInc' in criterias instead of criterias['SumInc'] is not None because in your case if there is no 'SumInc' it will raise you a KeyError exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download