For example, from my current project:
self.updated_at = datetime.strptime(kwargs.get("updated_at", None), datetime_format)
self.timestamp = datetime.strptime(kwargs.get("timestamp", None), datetime_format)
Those lines are used to instantiate an instance of a class in my program.
Obviously, if the default, None
, is passed to datetime.strptime
, I will get an exception, probably a TypeError
(I haven't tested it). I wish to make both of these variables default to None
in case of that error, or else avoid the error entirely.
I could wrap them with a function like this (noticed after the fact that it's a decorator):
def wrap_throwable(func, *exc):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc:
return None
return wrapper
And then the assignments in the class:
self.updated_at = wrap_throwable(
lambda: datetime.strptime(
kwargs["updated_at"],
datetime_format),
KeyError)()
self.timestamp = wrap_throwable(
lambda: datetime.strptime(
kwargs["timestamp"],
datetime_format),
KeyError)()
I haven't tested the code, but it's an idea. I'm wanting to know if there's a way to do this without creating another utility function, as shown above.