Skip to content

Instantly share code, notes, and snippets.

@Leonidas-from-XIV
Created November 30, 2011 01:02
Show Gist options
  • Save Leonidas-from-XIV/1407462 to your computer and use it in GitHub Desktop.
Save Leonidas-from-XIV/1407462 to your computer and use it in GitHub Desktop.
Python API equivalences in Clojure

Python API equivalences in Clojure

I tend to write rather functional code in Python so when I switch to Clojure I don't have to learn lots of things. Yet I often forget how to express some concepts in Clojure.

Infinite sequences

itertools.count(0) becomes (iterate inc 0)

Ranges

range(1, 10, 2) becomes (range 1 10 2). So obvious that I don't expect it.

For loop syntax

for x in ...: body becomes (for [x ...] body). Actually, this is more like a generator expression and is way more powerful. But that's the simple case.

Separating lists on some predicates

I don't know a direct Python version in the Stdlib, but clojure.contrib.seq.separate is a useful solution in Clojure.

Reading files line-wise

To read files line-wise, like popular in Python by iterating over file objects, clojure.contrib.duck-streams.read-lines can be used, which returns a line Seq.

Merging dictionaries

In Python the extend method can be used. Clojure has a nice merge-with function, to merge data structures.

Reducing

Clojures reduce is quirky, behaves a bit differently depending on how many arguments you specify. Might be worth a look.

Currying

Both Clojure and Python have partial, use it.

Function composition

In Python there are libraries for this, Clojure comes directly with a comp function that can be used to compose multiple functions.

Attribute getting

In Python there is operator.attrgetter to get an attribute from an object. In Clojure the key names :keyname can be used directly as accessor functions.

@lucian1900
Copy link

It's dict.update, not dict.extend. And sadly there's no immutable version.

@JamesTheAwesomeDude
Copy link

JamesTheAwesomeDude commented Jul 9, 2021

Have you found a Python equivalent for iterate?

I ended up just "polyfilling" this myself due to not spotting anything like it in the standard library...

def iterate(f, x):
    while True:
        yield (x := f(x))

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