loading...
Cover image for Python/Cython/Nim CheatSheet

Python/Cython/Nim CheatSheet

juancarlospaco profile image Juan Carlos Updated on ・6 min read

Who

Its meant to compare friendliness of writing and easy reading.
No performance benchmark.

Wat

Python 3 to Cython CheatSheet, with short examples, as simple as posible,
because I cant find a Cython Cheatsheet on Internet. It also adds Nim.
It start with simple stuff and continues towards more complex ones.
All values and variable names are example values.

Cython and Nim are alternatives to make Python faster (Compiled) and safer (Strong Static Typing).

Compiling

CheatSheet: Python, Cython, Nim

Small Integers

  • Python dont have Types for Medium Integers nor Small Integers.

Cython (Medium Integers)

cdef int a
a = 1

Nim + NimPy

var a = 1

Big Integers

Python

a = 100000000

Cython

cdef longlong a
a = 100000000

Nim + NimPy

var a = 100000000
  • Nim optionally can use explicit int8(), int16(), int32(), int64(), int().

Unsigned Integers

  • Python doesnt have Types for Positive Integers nor Unsigned Integers.

Cython (Unsigned Positive Integers)

ctypedef unsigned a
a = 1

Nim + NimPy

var a = Positive(1)
  • Nim has Positive() starting at 1 and Natural() starting at 0.
  • Nim optionally can use explicit uint8(), uint16(), uint32(), uint64(), uint().
  • Cython doesnt have Types for non-Zero values.

Strings

Python

a = "foo"

Cython

cdef char* a
a = "foo"

Nim + NimPy

var a = "foo"

F-Strings

Python

a = f"foo {variable} {1 + 2} bar"
  • Cython doesnt have F-Strings Types.

Nim + NimPy

import strformat

var a = fmt"foo {variable} {1 + 2} bar"
  • Nim needs import strformat, they can be compile-time.

Small Floats

  • Python doesnt have Types for Small Floats.

Cython (Small Floats)

cdef double a
a = 1.0

Nim + NimPy

var a = 1.0

Big Floats

  • Python doesnt have Types for Medium Floats.

Cython (Medium Floats)

cdef long double a
a = 1.000001

Nim + NimPy

var a = 1.000001

Python (Big Floats)

a = 1.0000000001

Cython (Big Floats)

cdef longlong double a
a = 1.0000000001

Nim + NimPy

var a = 1.0000000001
  • Nim optionally can use explicit float32(), float64(), float().

Booleans

Python

a = True

Cython

cdef bint a
a = True

Nim + NimPy

var a = true
  • Nim optionally can use the alias on for True, off for False.

Functions

Python

def foo(bar: str, baz: bool) -> int:
    return 1

Cython

cdef int foo(char bar, bint baz)
def foo(bar: str, baz: bool) -> int:
    return 1

Nim + NimPy

proc foo(bar: string, baz: bool): int =
    return 1
  • Nim optionally can use auto for return Type, it will inference the return Type.
  • Nim optionally can use any for argument Type, it will inference the argument Type.
  • On Nim arguments of a function are immutable by default.
  • Nim optionally can use func instead of proc for pure-functions Functional Programming (Side-Effect Free).

Methods

Python

def foo(self, bar: str, baz: bool) -> int:
    return 1

Cython

cdef int foo(self, char bar, bint baz)
def foo(self, bar: str, baz: bool) -> int:
    return 1

Nim + NimPy

proc foo(self: ObjectHere, bar: string, baz: bool): int =
    return 1
  • ObjectHere added for clarity.

Inlined Functions

  • Python doesnt have Inlined Functions.

Cython

cdef inline int foo(char bar, bint baz)
def foo(bar: str, baz: bool) -> int:
    return 1
  • Cython adds inline on cdef to inline a function.

Nim + NimPy

proc foo(bar: string, baz: bool): int {.inline.} =
    return 1
  • Nim adds {.inline.} Pragma to inline a function.

Lambdas

Python

from typing import Callable

variable: Callable[[int, int], int] = lambda var1, var2: var1 + var2

Nim + NimPy

( proc (var1, var2: int): int = var1 + var2 )
  • Python you are forced to put it on a variable for Type Annotations, Nim anonymous functions are Typed by itself.
  • Python Lambdas are not supported on Cython.
  • Python Lambda syntax is very different from function.
  • Nim anonymous functions are just functions without name.
  • Nim anonymous functions optionally can be func for pure-functions Functional Programming (Side-Effect Free).
  • Parens added for clarity.

Classes

Python

class MyObject(object):
  """ Documentation Here, plain-text by default """
  pass

Nim + NimPy

type MyObject = object  ## Documentation Here, **MarkDown** or *ReSTructuredText*

Comments & DocStrings

Python

# This is a comment

""" This is a DocString, plain-text by default """

Cython

# This is a comment

""" This is a DocString, plain-text by default """

Nim + NimPy

# This is a comment

## This is a Documentation Comment, **MarkDown** or *ReSTructuredText*
  • Nim can generate HTML, LaTex, JSON documentation by itself, no third party tool required.
  • NimPy puts Documentation Comments on the __doc__ as expected.

JSON

Python

import json

variable = json.loads("""{
  "key": "value",
  "other": true
}
""")

  • Cython doesnt have JSON Types.

Nim + NimPy

import json

var variable = %*{
  "key": "value",
  "other": true
}
  • Nim uses Literal JSON as-is directly on the code, not a multi-line string.

SubRanges

  • Python doesnt have SubRange Types.
  • Cython doesnt have SubRange Types.

Nim + NimPy

var subrange_integer: range[1..3] = 2
var subrange_float: range[1.0..3.0] = 2.5

var subrange_negative_integer: range[-3..-1] = -2
var subrange_negative_float: range[-3.0..-1.0] = -2.5
  • subrange_integer only takes values from 1 to 3.
  • subrange_float only takes values from 1.0 to 3.0.
  • subrange_negative_integer only takes values from -3 to -1.
  • subrange_negative_float only takes values from -3.0 to -1.0.

Static Constants

  • Python doesnt have Static Constants (Wont compile).
  • Cython doesnt have Static Constants (or is recommended to not use them?).

Nim + NimPy

const static_constant = 2 + 2
  • static_constant is immutable, compile-time pre-computed value.

Immutables

  • Python doesnt have run-time immutable variables.
  • Cython doesnt have run-time immutable variables.

Nim + NimPy

const foo = "Compile-Time Immutable Constant"
let bar = "Run-Time Immutable Variable"
var baz = "Run-Time Mutable Variable"

Compile-Time Function Execution

  • Python doesnt have Compile-Time Function Execution (Wont compile).
  • Cython doesnt have Compile-Time Function Execution.

Nim + NimPy

let compile_time_sum = static(1 + 2)

static:
  assert 4 > 2, "Compile-Time Assert"
  const compile_time_config = static_read("config.ini")
  • Everything you put inside static: or static() will be run at compile-time.

Miscelaneous

File Read Write

Python / Cython

with open("file.txt", "r") as infile:
    content = infile.read()

with open("file.txt", "w") as outfile:
    outfile.write("some data")

Nim

var content = read_file("file.txt")
write_file("file.txt", "some data")
  • Cython even if its compiled can not read files at compile-time, but Nim static_read() can.

Nim

const content = static_read("file.txt")
  • Nim static_read() is a compile-time read_file(), so the Cython version is run-time while the Nim version is compile-time.

Module Self-Executions

Python / Cython

if __name__ in "__main__":

Nim

when is_main_module:
  • Nim when is a compile-time if, so the Cython version is run-time while the Nim version is compile-time.

Compile-time help messages

  • Cython doesnt have a way to print compile-time help messages for users.

Nim

{.hint:    "This is a Hint, printed at Compile-Time, with colors too" .}
{.warning: "Warning Pragma, is Compile-Time, produces no extra code" .}

Thank you for playing

👑

Posted on Oct 2 '19 by:

juancarlospaco profile

Juan Carlos

@juancarlospaco

.10x frAgile FullStuck Midend Devlooper, Python & Nim, Arch & OpenSource, EN|ES

Discussion

markdown guide
 

This comparison cheatsheet looks awesome, thanks a lot!

Congrats Nim team for hitting 1.0 (one week ago😝)!