Using closures and partial functions to eliminate redundant code

Paul Hankin paul.hankin at gmail.com
Thu Sep 27 04:28:53 EDT 2007


On Sep 27, 3:01 am, Matthew Wilson <m... at tplus1.com> wrote:
> I wrote some code to create a user and update a user on a remote box by
> sending emails to that remote box.  When I was done, I realized that my
> create_user function and my update_user function were effectively
> identical except for different docstrings and a single different value
> inside:
>
>     ### VERSION ONE
>
>     def create_user(username, userpassword, useremail):
>         "Send an email that will create a user in the remote system."
>
>         # Build email
>         email_body = """
>     USERNAME = %s
>     USERPASSWORD = %s
>     USEREMAIL = %s
>     """ % (username, userpassword, useremail)
>
>         # send it.
>         send_email(subject="CREATE", body=email_body)
>
>     def update_user(username, userpassword, useremail):
>         "Send an email that will update a user's password in the remote system."
>
>         # Build email
>         email_body = """
>     USERNAME = %s
>     USERPASSWORD = %s
>     USEREMAIL = %s
>     """ % (username, userpassword, useremail)
>
>         # send it.
>         send_email(subject="UPDATE", body=email_body)

If you don't mind what order the lines of your email appear in, you
might get more reuse out of something like this. As other's have said
partial isn't needed here.

def send_command_email(subject, **kwargs):
    """Send an email to the with the given subject, and lines of the
       body of the form A = B for each keyword argument."""
    email_body = '\n'.join('%s = %s' % (k, kwargs[k]) for k in kwargs)
    send_email(subject=subject, body='\n' + email_body + '\n'

def create_user(name, password, email):
    "Create a user by sending an email to the server"
    send_command_email('CREATE', USERNAME=name,
        USERPASSWORD=password, USEREMAIL=email)

def update_user(name, password, email):
    "Update a user's details by sending an email to the server"
    send_command_email('UPDATE', USERNAME=name,
        USERPASSWORD=password, USEREMAIL=email)

--
Paul Hankin




More information about the Python-list mailing list