Is function argument reuse for multiple types in Python 3.4 pythonic and how does it relate to duck typing? Should I split the function?

I'm coming from C # and Java, so losing text input is still new to me, it might seem.

I have a function that drops a query to the database to remove duplicates that have happened recently. Let's say the last 14 days or so. When the script runs on a daily basis, I would like it to return only using an integer number of days, for example 14; however, sometimes I may need to provide a date and time in order to use it directly, instead of figuring out which date would be by subtracting an integer.

I am currently seeing the following:

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 and use dup_start_str in a query.

      

Is this the correct use of duck? Is this python?

My alternative, from the top of my head, is to split the two 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 and use dup_start_str in a query.

      

(encoded this last bit in the browser, so can be disabled)

+3


source to share


1 answer


Duck printing means that you are assuming that the object contains a function, and if so, then everything just works.

If an alternative path exists, if the function does not exist, intercept it with 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')

      

+1


source







All Articles