[Tutor] pythonic

Peter Otten __peter__ at web.de
Fri Mar 30 05:22:35 EDT 2018


Pat Martin wrote:

> I have written the following program. It generates a template for Pelican
> web site static generator. It works just fine, it generates the template
> and then I put the info in it to customize. But I was wondering, is this
> the "right" way to do it in python?

You may rewrite the code creating the output as a loop:

    now_str = now.replace(microsecond=0).isoformat(" ")
    with open("{}.md".format(slug), 'w') as f:
        for name, value in [
                ("Title", args.title),
                ("Date", now_str),
                ("Modified", now_str),
                ("Category", args.category),
                ("Slug", slug),
                ("Authors", args.author),
                ("Summary", ""),
        ]:
            print(name, value, sep=": ", file=f)


If you want to format more than one date the same way you should put the 
code into a function, no matter whether you pick your, my, or Alan's much 
more common way to implement it

def format_time(dt):
   return ...

...
                ("Date", format_time(now)),
                ("Modified", format_time(modified)),
...

The idea behind my suggestions is the DRY (don't repeat yourself) principle 
which applies to code written in any language.

> #!/usr/bin/env python3
> """Generate a Pelican markdown base page."""
> 
> import argparse
> import datetime
> 
> 
> def Main():
>     """Run if run as a program."""
>     parser = argparse.ArgumentParser()
>     parser.add_argument("-T", "--title", type=str, required=True,
>                         help='Title for site, also generates the slug',
>                         metavar="")
>     parser.add_argument("-c", "--category", required=True,
>                         help='Category or categories of post', metavar="")
>     parser.add_argument("-t", "--tags", type=str, required=True,
>                         help="Tags for post", metavar="")
>     parser.add_argument("-a", "--author", type=str, default="Pat Martin",
>                         help="Author of post", metavar="")
>     args = parser.parse_args()
> 
>     now = datetime.datetime.now()
>     slug = args.title.replace(" ", "-").lower()
> 
>     with open("{}.md".format(slug), 'w') as f:
>         f.write("Title: {}\n".format(args.title))
>         f.write("Date: {}-{}-{} {}:{}\n".format(now.year,
>                                                 now.month,
>                                                 now.day,
>                                                 now.hour,
>                                                 now.minute))
>         f.write("Modified: {}-{}-{} {}:{}\n".format(now.year,
>                                                     now.month,
>                                                     now.day,
>                                                     now.hour,
>                                                     now.minute))
>         f.write("Category: {}\n".format(args.category))
>         f.write("Slug: {}\n".format(slug))
>         f.write("Authors: {}\n".format(args.author))
>         f.write("Summary: \n")
> 
> 
> if __name__ == "__main__":
>     Main()




More information about the Tutor mailing list