JeyKey
JeyKey

Reputation: 423

How to pass function with specific input to function which validates this input? - Python

I am using MVC (Module-View-Controller) pattern in my project. I want to keep my code DRY(Don't repeat yourself) so I don't want to write get_date function again just for another input.

I use function get_date() several times, but with different inputs. How can I pass these inputs to function get_date() so it could work?

Here I call get_date() function:

date = get_date(date_input = provide_date())

Here I want to pass the function with input message:

def get_date(date_input):
    ask = True
    while ask:
        date_input
        try:
            validation = datetime.strptime(date_input, '%Y-%m-
%d').strftime('%Y-%m-%d')
            date_list = validation.split('-')
            correct_date = 
date(int(date_list[0]),int(date_list[1]),int(date_list[2]))
            return correct_date
            ask = False
        except ValueError:
            wrong_input()

Provide_date function is:

def provide_date():
    return input('Type date in format Y-M-D: ')

I have another inputs for different situations like reschedule with another message.

How can I pass this input to get_date() function so it could work inside While loop? Cause now it loops forever when I raise TypeError.

Upvotes: 1

Views: 90

Answers (1)

tobias_k
tobias_k

Reputation: 82899

There are a few problems with your code:

  • you call the function and then pass the result to get_date; instead, pass the function itself
  • then, call the function within get_date, and also bind the result to some variable
  • no need to parse the date, then format it, then parse it again, manually
  • since you return from the function, no need for the ask variable

Try this:

def get_date(date_input):
    while True:
        inpt = date_input()  # add () and bind result to variable
        try:
            dt = datetime.strptime(inpt, '%Y-%m-%d')  # no need to parse-format-parse
            return date(dt.year, dt.month, dt.day)  # use attributes of parsed datetime
        except ValueError:
            wrong_input()

print(get_date(provide_date))  # no () here

Upvotes: 1

Related Questions