AutomaticStatic
AutomaticStatic

Reputation: 1739

Python: Convention for date with no year

I have a script that looks at a list of birthdays and then calculates the age. Some birthdays have year, month, day and some only have month, day.

For the ones with years, I have dob = date(year, month, day)

But for the ones without years, what is the appropriate convention for storing the date, since date() requires a year argument?

Right now I'm saying that everyone without a birth year was born in the year 1500 (so I can at least identify them easily later on), but it's obviously a stupid solution.

Upvotes: 7

Views: 2806

Answers (2)

tyrex
tyrex

Reputation: 8879

I think it pays off to go a small extra mile when defining data structures (not with other things!) and not use a convention like your year 1500. Thus:

from dataclasses import dataclass

@dataclass
class Birthday:
    day: int
    month: int
    year: Optional[int] = None

    def is_valid(self) -> bool:
        try:
            dt = date(self.year, self.month, self.day)
            return True
        except ValueError:
            return False

The dataclass is for extra convenience only when creating or printing a birthday. Now you can:

birthday_without_year = Birthday(day=3, month=5)
birthday_with_year = Birthday(day=3, month=5, year=2000)

If you want, you can overwrite the default __init__ and check if the birthday is_valid if someone passes a year.

Upvotes: 2

jfs
jfs

Reputation: 414655

If there is no year; don't use datetime.date class. date must have year. Either compute date field on the fly everytime you need it if year is present, and/or make self.date property on your custom object to raise an error if it is used for an object without a year.

Upvotes: 4

Related Questions