parasit
parasit

Reputation: 506

Intentionally returning None instead of object

Suppose I have two simple classes:

@dataclass
class Item():
  Name: str
  Valie: float

class Registry():
  items = []
  
  def __init__(self):
    # load some items from external source, etc

  """ find an element in an array or return None """
  def find(self, name: str) -> Item:
    for i in self.Items:
      if i.Name = name: # items are unique, 
         return i
    return None # ignore type 

Without this #ignore type got warning Expression of type "None" cannot be assigned to return type "Item". Ok, I understand why. But is this the right approach or is there a better more "pythonic" way to solve this problem? i.e. returns nothing if it is not in the list.

On the "other side" is something like:

item = registry.find(name)
if item != None:
  doSomething()

Upvotes: 1

Views: 84

Answers (1)

Unmitigated
Unmitigated

Reputation: 89412

Change the type hint to Optional[Item] which allows either Item or None (equivalent to Item | None).

from typing import Optional

def find(self, name: str) -> Optional[Item]:

See also: https://docs.python.org/3/library/typing.html#typing.Optional

Upvotes: 4

Related Questions