[Tutor] How to refactor a simple, straightforward script into a "proper" program?

Mats Wichmann mats at wichmann.us
Sat Jan 4 18:45:45 EST 2020


On 1/4/20 4:05 PM, boB Stepp wrote:
> Thank you, Joel, for your comments.  I have found them valuable.
...
> One question I do wish to ask up front:  _If_ type annotations are
> used, does this affect how the code is documented?  My impression is
> that with my code as is (no type annotations) I should have added a
> section for each function explaining the expected type and function of
> each parameter and value returned.  But if I do use type annotations,
> that would seem redundant.

I think there may not be full consensus yet, as type hints are still 
kind of new to people, and with many people having to live with Python 2 
use, either "until recently" or "for a while yet because of our 
project", haven't really been fully utilized. The idea is to convey 
information so it's useful to humans _and_ to tools you may choose to 
use. If you were targeting a Python version that didn't have the hints, 
they had to go in an external hints file for the tools to find, and that 
provides no help to human readers. In 2020, maybe that consideration 
isn't as important, with many people able to target just "modern" Python.

Yes, if you have a type hint, the type part of docstring parameter 
markup is redundant, and can be left out. You probably still want to say 
other things about the parameter, however.

That is, unannotated, you could express validate_input_parameters as 
(using the "Google docstring format"):

def validate_input_params(num_pages_in_book, num_pages_read, goal_date):
     """Verify input parameters for logical correctness.

     Args:
         num_pages_in_book (int): number of pages available
         num_pages_read (int): number of pages read
         goal_date (datetime.date): target finish date

     Returns:
         bool: input validity

     """

but with annotations, maybe:

def validate_input_params(num_pages_in_book: int, num_pages_read: int, 
goal_date: datetime.date) -> bool:
     """Verify input parameters for logical correctness.

     Args:
         num_pages_in_book: number of pages available
         num_pages_read: number of pages read
         goal_date: target finish date

     """

Or not... as you know, there's nothing mandatory about this, it's how 
you think the information is best conveyed - to future you, and to any 
other readers (or if part of a larger project, following the conventions 
that project follows).  You could argue, for example, that you've chosen 
such exquisite variable names that you don't need to bother saying what 
they're for.  In the case of this function, that wouldn't be a totally 
off-base assertion.



More information about the Tutor mailing list