Example from Raymond Hettinger's talk, "Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From "Raymond Hettinger - Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015" | |
# Bad code | |
import jnettools.toolselements.NetworkElement, \ | |
jnettools.tools.Routing, \ | |
jnettools.tools.RouteInspector | |
ne=jnettools.tools.elements.NetworkElement( '171.0.2.45' ) | |
try: | |
routing_table=ne.getRoutingTable() #fetch table | |
except jnettools.tools.elements.MissingVar: | |
# Record table fault | |
logging.exception ( '''No routing table found''' ) | |
# Undo partial changes | |
ne.cleanup( '''rollback''' ) | |
else: | |
num_routes=routing_tables.getSize() # determine table size | |
for RToffset in range( num_routes ): | |
route=routing_table.getRouteByIndex( RToffset ) | |
name=route.getName() # route name | |
ipaddr=route.getIPAddr() # ip address | |
print "%15s -> %s"% (name,ipaddr) # format nicely | |
finally: | |
ne.cleanup( ''''commit''' ) # lockin changes | |
ne.disconnect() | |
# First refactoring | |
import jnettools.toolselements.NetworkElement | |
import jnettools.tools.Routing | |
import jnettools.tools.RouteInspector | |
ne = jnettools.tools.elements.NetworkElement('171.0.2.45') | |
try: | |
routing_table = ne.getRoutingTable() | |
except jnettools.tools.elements.MissingVar: | |
logging.exception ('No routing table found') | |
ne.cleanup('rollback') | |
else: | |
num_routes = routing_tables.getSize() | |
for RToffset in range(num_routes): | |
route = routing_table.getRouteByIndex(RToffset) | |
name = route.getName() | |
ipaddr = route.getIPAddr() | |
print "%15s -> %s"% (name,ipaddr) | |
finally: | |
ne.cleanup('commit') | |
ne.disconnect() | |
# Second refactoring | |
from nettools import NetworkElement | |
with NetworkElement('171.0.2.45') as ne: | |
for route in ne.routing_table: | |
print "%15s -> %s" % (route.name, route.ipaddr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a typo (missing dot between
tools
&elements
) in the first import in the original and the first refactoring examples.But what I found strange in the original code were the imports altogether - I don't think the code was ever actually run :-)
import jnettools.tools,elements.NetworkElement
should likely befrom jnettools.tools.elements import NetworkElement
(unless some code before messed withsys.modules
:-) )jnettools.tools.Routing
&jnettools.tools.RouteInspector
imports seem superfluous altogether (unless they do something silly like dynamically register themselves with the system somewhere upon import instead of getting imported by the code using them :-))