amay20
amay20

Reputation: 147

Dictionary .get() method

self.dictionary.get(tuple_row_column, self.raiseError())
  1. Is there a way to raise an Error without defining a method that will manually raise the Error?
  2. Even when the dictionary contains the key, the method self.raiseError() is called. Why is that?

Upvotes: 1

Views: 226

Answers (2)

Bahrom
Bahrom

Reputation: 4862

That is because .get first evaluates the default parameter, as it needs to know what to return in case of a missing key. As pointed out in the comments - if your dictionary contains anything boolean of which evaluates to a False (like empty strings, 0, False, [], etc.) this approach will raise an error self.dictionary.get(tuple_row_column) or self.raiseError(); either way, the bracket lookup is more pythonic if you want to raise an error if there's a missing key.

For your first question you could just do

self.dictionary[tuple_row_column] # Raises KeyError if tuple_row_column not present in dictionary keys.

If you want it to raise your error, you could say:

try:
    self.dictionary[tuple_row_column]
except KeyError:
    self.raiseError()

Upvotes: 1

Chris Martin
Chris Martin

Reputation: 30746

Python is strictly evaluated, meaning that all of the arguments to a function call are evaluated before the function is called. So self.raiseError() necessarily runs, regardless of whether it's needed (in contrast with non-strict or "lazy" languages that do not have this limitation).

If you use subscripting instead of get:

self.dictionary[tuple_row_column]

this will raise KeyError if there is no mapping.

Upvotes: 2

Related Questions