[Tutor] Code critique

Japhy Bartlett japhy at pearachute.com
Fri Oct 24 21:32:56 CEST 2014


out = stdout.read()
if '3102EHD-Lanka-1108' in out:
        s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh')
        sftp = s.open_sftp()
        sftp.get('/Downloads/Hourly/3102EHD-01108/3102EHD-01108.png',
'/Downloads/Hourly/3102EHD-01108.png')
        sftp.close()
        print 'file recieved'
elif '3102EHD-01109' in out:
        s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh')
        sftp = s.open_sftp()
        sftp.get('/Downloads/Hourly/3102DHD-01109/3102DHD-01109.png',
'/Downloads/Hourly/3102DHD-01109.png')
        sftp.close()
        print 'file recieved'
...

----
could be something like:
----

params = {
    '3102EHD-Lanka-1108': '3102EHD-01108',
    '3102EHD-01109': '3102DHD-0119',
    # ... etc, for each of those elif choices
    }

# one function with a variable for the parts that change
function dosomething(identifier):
    s.exec_command('export DISPLAY=:0.0; cd /Downloads/Hourly/win.sh')
    sftp = s.open_sftp()
    sftp.get('/Downloads/Hourly/{}/{}.png'.format(identifier,identifier),
'/Downloads/Hourly/{}.png'.format(identifier))
    sftp.close()
    print 'file recieved'

# do this as usual
out = stdout.read()

# then call the function with the variable
dosomething(params[out])



----

with a bit of work, it seems like that could be simplified even more, but
the general idea is that the elif blocks with lots of boilerplate repeated
over and over is generally a sign of bad/lazy code.


On Fri, Oct 24, 2014 at 1:50 PM, Bo Morris <crushed26 at gmail.com> wrote:

> "...Regarding your program, instead of writing long sequences of
> repetitive if
> conditions, I would write one function for each of the different operations
> and store them in a dict, mapping each host name to a function (and
> multiple host names may map to the same function). Then, look up the host
> name in the dict and call the corresponding function to run the right
> operations on that host..."
>
> Thank you Stefan for your input. Would please be willing to provide an
> example?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141024/26062e70/attachment-0001.html>


More information about the Tutor mailing list