What are the top gotchas for someone moving from a static lang (java/c#) to dynamic language like python?
It seems cool how things can be done, but renaming a method, or adding/removing parameters seems so risky!
Is the only solution to write tests for each method?
I would say that the number one gotcha is trying to write statically typed code in a dynamic language.
Dont hesitate to use an identifier to point to a string and then a list in self-contained sections of code
don’t hesitate to treat functions like regular values: they are. Take the following parser. Suppose that we want to treat all header tags alike and ul tags like ol tags.
This could be done by using less generic code in the
handle_starttagmethod in a language like java by keeping track of which tags map to the same method but then if you decide that you want to handle div tags, you have to add that into the dispatching logic. Here you just add the methodparse_divand you are good to go.Don’t typecheck! Duck-type!
as opposed to
isinstance(arg, Foo). This lets you pass in any object withattr1andattr2. This allows you to for instance pass in a tracing class wrapped around an object for debugging purposes. You would have to modify the class to do that in Java AFAIK.As pointed out by THC4k, another (more pythonic) way to do this is the EAPF idiom.
I don’t like this because I like to catch errors as early as possible. It is more efficient if you expect for the code to rarely fail though. Don’t tell anybody I don’t like it though our they’ll stop thinking that I know how to write python. Here’s an example courtesy of THC4k.
It’s a tossup as to if we should be catching the
AttributeErrorandTypeErroror just let them propagate to somewhere that knows how to handle them but this is just an example so we’ll let it fly.