Skip to content

Instantly share code, notes, and snippets.

@jkoppel
Created September 16, 2017 19:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkoppel/201c0a48702128e1de99eeed0d081c7b to your computer and use it in GitHub Desktop.
Save jkoppel/201c0a48702128e1de99eeed0d081c7b to your computer and use it in GitHub Desktop.
Example from Raymond Hettinger's talk, "Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015"
# 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)
@jurko-gospodnetic
Copy link

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 be from jnettools.tools.elements import NetworkElement (unless some code before messed with sys.modules :-) )
  • and the 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 :-))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment