Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize parameter of method with default value

Tags:

python

I would like to initialize a method's parameter with some default value if an explicit value was not passed into the method - something like this:

class Example
   def __init__(self, data = self.default_data()):
      self.data = data

   def default_data():
      # ....
      return something

I got the error:

NameError: name 'self' is not defined

How do I fix this?

like image 416
ceth Avatar asked Oct 25 '12 18:10

ceth


People also ask

Can parameters have default values?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

What is default parameter can we use default parameter for first parameter in function?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.


1 Answers

The common idiom here is to set the default to some sentinel value (None is typical, although some have suggested Ellipsis for this purpose) which you can then check.

class Example(object): #inherit from object.  It's just a good idea.
   def __init__(self, data = None):
      self.data = self.default_data() if data is None else data

   def default_data(self):  #probably need `self` here, unless this is a @staticmethod ...
      # ....
      return something

You might also see an instance of object() used for the sentinel.

SENTINEL = object()
class Example(object):
   def __init__(self, data = SENTINEL):
      self.data = self.default_data() if data is SENTINEL else data

This latter version has the benefit that you can pass None to your function but has a few downsides (see comments by @larsmans below). If you don't forsee the need to pass None as a meaningful argument to your methods, I would advocate using that.

like image 184
mgilson Avatar answered Sep 22 '22 09:09

mgilson