The default value for an optional argument in Python:

I have the following method:

def get_data(replace_nan=False):
    if replace_nan is not False
        data[numpy.isnan(data)] = replace_nan
        return data
    else:
        return data[~numpy.isnan(data)]

So, if it replace_nanis False, we return some data array, but delete NaNs, and if it is something else, we replace it with an NaNargument.

The problem is that I can replace NaNwith False. Or anything else for the sake of it. What is the most pythonic way to do this? It:

def get_data(**kwargs):
    if "replace_nan" in kwargs:
       ...

works, but semantically ugly (because we are really only interested in one keyword argument, replace_nan). Any suggestions for handling this case?

+3
source share
4 answers

Usually people use Noneas default and then check for is not None.

None, :

__default = object()
def get_data(replace_nan=__default):
    if replace_nan is __default:
        ...
+4

numpy False 0:

    >>>np.array([False,True,2,3])
    array([0, 1, 2, 3])

, , , .

    def get_data(replace_nan=False):
       if replace_nan:
          return np.where(np.isnan(data),replace_nan,data)
       else:
          return data[~numpy.isnan(data)]

numpy.where , NaN. replace_nan, , .

:

numpy.where(condition[, x, y])
Return elements, either from x or y, depending on condition.
+2

ThiefMaster, , ...:

, - - del .

__default = object()
def get_data(replace_nan=__default, __default=__default):
  if replace_nan is __default:
    ...
del __default

:

__default = object()
def get_data(replace_nan=__default):
  if replace_nan is get_data.default_replace_nan:
    ...
get_data.default_replace_nan = __default
del __default
+1

ThiefMaster :

def get_data(replace_nan=object()):
  if replace_nan is get_data.func_defaults[0]:
    ...

python interna, (pypy/stackles/next version/...).

+1

All Articles