ealeon
ealeon

Reputation: 12452

Python: dealing with None parameters

What is the best practice?
1) have a function be able to take in None?
2) practice to not to send None to a func

is it just personal preference or are there any pros/cons to this?

I have a func

def parse_path(path):
    site = None

    site_pattern = re.compile('(fl|ny|wa|tx)')
    match = site_pattern.search(path)
    if match:
        site = match.group(0)

    return site

so obviously if i pass in None to parse_path, it will complain.
TypeError: expected string or buffer

so should I always be conscious of what to put in to a func or should a func be flexible so it deals with None?

Upvotes: 3

Views: 316

Answers (1)

Zak
Zak

Reputation: 3253

I'm using None as default sometimes as in:

def dosomething(input1, input2=None):

    if not input2:
        input2 = compute_default_input2

    carry_on()
    ....

This can be useful in classes that can be used in multiple ways or where certain properties require computationally intense initialisation, so you don't want to do this unless it's requested -- adding None as default makes that possible. It's also a cheap way to allow users to override an object's properties:

def dosomething(self, property=None):

    if not property:
        property = self.property

This will use the self.* value by default but allow the user to override it. It's also something of a hack, so as most things in Python should probably used with care.

... other than that: I think None as an input should only be dealt with in a function if there's a reasonable use case where None is passed to that function, and that very much depends on the environment that it is operating in. If you can reasonably expect everyone to be aware they shouldn't call your function with None then the standard error message from Python should be enough to make clear what the problem is.

Upvotes: 2

Related Questions