Is reuse of a function argument for multiple types in Python 3.4 pythonic, and how does it relate to duck typing? Should I split the function up? -
i come c# , java, lose typing still new me, might show.
i have function shoots of query a database remove duplicates have occurred lately. say, withing last 14 days or so. when script runs daily i'd lookback using integer of days 14; however, might want supply datetime , have use directly instead of calculating date subtraction of integer.
the following pretty have @ moment:
def clean_up_duplicates(dup_lookback): if hasattr(dup_lookback, 'strftime'): dup_start_str = dup_lookback.strftime('%y-%m-%d %h:%m:%s') else: dup_start = date.today() - timedelta(days=dup_lookback) dup_start_str = dup_start.strftime('%y-%m-%d %h:%m:%s') # ... continue on , use dup_start_str in query. is correct use of ducktyping? pythonic?
my alternative, of top of head, split in 2 functions:
def clean_up_duplicates_since_days(dup_lookback_days): dup_start_str = dup_lookback.strftime('%y-%m-%d %h:%m:%s') __clean_up_duplicates(dup_start_str) def clean_up_duplicates_since_datetime(dup_lookback_datetime): dup_start = date.today() - timedelta(days=dup_lookback) dup_start_str = dup_start.strftime('%y-%m-%d %h:%m:%s') __clean_up_duplicates(dup_start_str) def __clean_up_duplicates(dup_start_str): # ... continue on , use dup_start_str in query. (coded last bit in browser, might off)
duck typing means assume object contains function, , if works.
if there's alternate path take if function doesn't exist, catch try/except.
def clean_up_duplicates(dup_lookback): try: dup_start_str = dup_lookback.strftime('%y-%m-%d %h:%m:%s') except attributeerror: dup_start = date.today() - timedelta(days=dup_lookback) dup_start_str = dup_start.strftime('%y-%m-%d %h:%m:%s')
Comments
Post a Comment