by BiteCode_dev · 5y ago · 0 comments
If you are used to call backs, promises, tick() calls or closures, it will be natural to reach for them a lot, and be disappointed at their state in the Python ecosystem.
But while I do miss better anonymous functions support sometimes in Python, it is rarely a problem because it comes with other tools to arrive to the same result.
Generators are one of them. Of course, you'll have to realize that generators are way more that a lazy way of generating data. You can use them for control flow, hold state, hide complexity or delegate behavior using a common interface. The send() method is very often completely ignored by most devs, and the yield from underused.
But beyond generators are a lot more things that, in the same vein, will bring you to python enlightenment once you start thinking with them instead of trying to make a Python fits into a square hole:
- the functools module
- the itertools module
- context managers
- any/all/zip/iter/next/enumerate
- decorators (it can do so much more than you imagine)
- type hints (take a look at fast api for awesomeness)
It's a real disappointment that Python has no answer for JavaScript fat arrow.
The fat arrow is the one construct that completely changes the structure of all the programs I write - it makes things extremely terse and I use it in nearly every function/method in some way.
I'm a big fan of Python's whitespace structure but it seems to be an obstacle to creating single line functions that are both powerful and get multiple things done, which sometimes makes a program easier to read and more understandable. Sure there's lambda functions but I find them clumsy and hard to work with compared to the beauty of the fat arrow.
But I also know by experience that people from other languages are reaching for anonymous functions way too often instead of using the tools that are suitable for the use case in python.
E.G: if you use a lot of map() and filter() in python, you are doing it wrong.
Maybe - but at the same time, generators are side-effectful and quite general. That means, when someone uses a generator, now I have to understand what happens by looking at the code. If someone uses a promise or a closure/lambda, then the scope of what can happen is much more limited.
It's like looping vs. mapping. You can use "for ... in ..." syntax or you can do "map(..., ...)" but I generally prefer the latter (minus the syntax overhead in python), simply because I easily see at a glance what the intend is.
In languages without generators it's easy to write code that traverses some data structure in hard-coded way and does something configurable on every node, but it's hard to write code that traverses a data structure in configurable way and does some hardcoded thing on every element.
In Python it's trivial both ways and even both at once.
Wouldn’t this just be a function that operates on an iterator? I suppose generators make the creation of lazy iterators easier, but generally the solution for languages without generators is to have your traversal build a list. So you lose the laziness but the code remains simple. Then map your per-node processing to the list.
Yes, but then you move from O(1) to O(n) in memory usage. And if you want to optimize it you have to restructure your code, when in python lists and generators are drop-in replacements.
Which other languages? Generator support is common:
https://en.m.wikipedia.org/wiki/Generator_(computer_programm...
Certainly in Java you can use the `Iterator` interface to get generator like behavior. But that's both a whole lot more complex and more verbose. Primarily because you have to coordinate the `hasNext` method with the `next` method.
With python and yield syntax, that naturally falls out without a bunch of extra code juggling.
Although some generator implementations are not as complete as python ones, and the ecosystem generally donc have much support for it
E.g : Very few languages have an equivalent to itertools.
def print_every_file_in(root_path):
for path in children(root_path):
if is_file(path):
print("file: " + path + ", size:" + get_size(path))
else:
print_every_file_in(root_path)
If you want to extract the printing part it's trivial in any language: def print_file(path):
print("file: " + path + ", size:" + get_size(path))
def print_every_file_in(root_path):
for path in children(root_path):
if is_file(path):
print_file(path)
else:
print_every_file_in(path)
And you can easily parametrize what function to call on each node.But in Python it's equally trivial to extract the traversal:
def every_file_in_path(root_path):
for path in children(root_path):
if is_file(path):
yield path
else:
yield from every_file_in_path(path)
def print_every_file_in(root_path):
for file in every_file_in_path(root_path):
print("file: " + path + ", size:" + get_size(path))
or even extract both: def print_every_file_in(root_path):
for file in every_file_in_path(root_path):
print_file(file)
which for me is a very clean way to implement this and it's nontrivial to do in languages without generators.needing to store state - use a class
needing lazy evalutaion - use a class (though this is a common enough use case to be a primitive, e.g. Kotlin)
decorators - if you pass decorated methods around -> now you have to remember the context the methods hold. Instead, refactor your code to be more direct so that you don't need decorators.
type hints - they are not fully enforceable at compile time, unless everything in your codebase has type hints. This is never the case and type hints can easily lull you into a false sense of security.
functools module - generally I'm ok with this but sonetimes you have to be aware of when you need to deep copy vs when you don't etc.
static IEnumerable<int> Fibonacci()
{
int first = 0;
int second = 1;
yield return first;
yield return second;
while (true)
{
(first, second) = (second, second + first);
yield return second;
}
} def _combined(args):
return decorator(args) and original(args)
It can also be applied retroactively, not just at the decorated function's definition. This is extremely handy in the context of configuring your text editor, but I admit I wouldn't like it in a program I was working on with other people. (Basically a form of monkeypatching.)* Granted not really used for general-purpose programming like Python.
[0]:https://www.gnu.org/software/emacs/manual/html_node/elisp/Ad...
edit, sorry I've meant generators. Incidentally, it's also true for js decorators.