Skip to content

Instantly share code, notes, and snippets.

@vermashresth
Created March 24, 2018 17:55
Show Gist options
  • Save vermashresth/41b39280a0cbad06cc01a90381b9c646 to your computer and use it in GitHub Desktop.
Save vermashresth/41b39280a0cbad06cc01a90381b9c646 to your computer and use it in GitHub Desktop.
Refactoring parse_time through single dispatch.
from functools import singledispatch
@singledispatch
def convert_time(time_string, **kwargs):
# default case when no type matches
return Time(time_string, **kwargs)
@convert_time.register(pandas.Series)
def convert_time_pandasSeries(time_string, **kwargs):
return np.array([Time(val, **kwargs) for val in time_string])
@convert_time.register(np.datetime64)
def convert_time_npdatetime64(time_string, **kwargs):
return Time(_parse_dt64(time_string), **kwargs)
@convert_time.register(np.ndarray)
def convert_time_npndarray(time_string, **kwargs):
return np.array([Time(_parse_dt64(val), **kwargs) for val in time_string])
@convert_time.register(str)
def convert_time_str(time_string, **kwargs):
# only include those string patterns which can't be handled by
# astropy.time.Time
...
# when no format matches, call default function that is,
# give it to astropy.time.Time to handle
convert_time.dispatch(object)(time_string, **kwargs)
def parse_time(time_string, **kwargs):
if time_string is 'now':
return Time.now()
else:
return convert_time(time_string, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment