21

Imagine I have the following code in javascript

function test(string) {
    var string = string || 'defaultValue'
}

What is the Python way of initiating a variable that may be undefined?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user3619165
  • 380
  • 1
  • 2
  • 13
  • The answers tell you how to have a parameter with a default value, but maybe you want this: http://stackoverflow.com/questions/23086383/how-to-test-nonetype-in-python – Paulo Almeida Mar 30 '16 at 23:16

3 Answers3

25

In the exact scenario you present, you can use default values for arguments, as other answers show.

Generically, you can use the or keyword in Python pretty similarly to the way you use || in JavaScript; if someone passes a falsey value (such as a null string or None) you can replace it with a default value like this:

string = string or "defaultValue"

This can be useful when your value comes from a file or user input:

string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"

Or when you want to use an empty container for a default value, which is problematic in regular Python (see this SO question):

def calc(startval, sequence=None):
     sequence = sequence or []
kindall
  • 178,883
  • 35
  • 278
  • 309
  • It's worth mentioning, for `None` specifically, do `string = string if string is not None else "defaultValue"`. Reference: [How to "test" NoneType in python?](https://stackoverflow.com/q/23086383/4518341) – wjandrea Jul 13 '22 at 14:54
  • I wouldn't use `sequence or`, cause it's too loose. For example, if I accidentally passed in the integer `0`, I'd expect a `TypeError`, but this'd silently use the default. This'd be better: `if sequence is None or len(sequence) == 0: sequence = []`. But thinking about that, why bother swapping out empty sequences? If you're actually intending to only replace `None`, do that explicitly instead of using `or`: `sequence = sequence if sequence is not None else []`. – wjandrea Jul 13 '22 at 15:13
6

For a function parameter, you can use a default argument value:

def test(string="defaultValue"):
    print(string)

test()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ruthless
  • 309
  • 3
  • 13
1

You can use default values:

def test(string="defaultValue")
    pass

See https://docs.python.org/2/tutorial/controlflow.html#default-argument-values

Dominic K
  • 6,975
  • 11
  • 53
  • 62