1

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.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49
  • @blhsing I saw the post that you marked this as a duplicate of. Did you look at the answers? That's the exact same methodology I used in my proposal of what I *didn't want*. – Jacob Birkett Mar 05 '19 at 22:21
  • Yes, and it has a one-line solution in the other answer there. It is otherwise impossible, as the main answer points out. – blhsing Mar 05 '19 at 22:23

0 Answers0