DEV Community

Cover image for Python/Cython/Nim CheatSheet
Juan Carlos
Juan Carlos

Posted on • Updated on

Python/Cython/Nim CheatSheet

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
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = 1
Enter fullscreen mode Exit fullscreen mode

Big Integers

Python

a = 100000000
Enter fullscreen mode Exit fullscreen mode

Cython

cdef longlong a
a = 100000000
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = 100000000
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = Positive(1)
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode

Cython

cdef char* a
a = "foo"
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = "foo"
Enter fullscreen mode Exit fullscreen mode

F-Strings

Python

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

Nim + NimPy

import strformat

var a = fmt"foo {variable} {1 + 2} bar"
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = 1.0
Enter fullscreen mode Exit fullscreen mode

Big Floats

  • Python doesnt have Types for Medium Floats.

Cython (Medium Floats)

cdef long double a
a = 1.000001
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

var a = 1.000001
Enter fullscreen mode Exit fullscreen mode

Python (Big Floats)

a = 1.0000000001
Enter fullscreen mode Exit fullscreen mode

Cython (Big Floats)

cdef longlong double a
a = 1.0000000001
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

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

Booleans

Python

a = True
Enter fullscreen mode Exit fullscreen mode

Cython

cdef bint a
a = True
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

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

Functions

Python

def foo(bar: str, baz: bool) -> int:
    return 1
Enter fullscreen mode Exit fullscreen mode

Cython

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

Nim + NimPy

proc foo(bar: string, baz: bool): int =
    return 1
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Cython

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

Nim + NimPy

proc foo(self: ObjectHere, bar: string, baz: bool): int =
    return 1
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • Cython adds inline on cdef to inline a function.

Nim + NimPy

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

Lambdas

Python

from typing import Callable

variable: Callable[[int, int], int] = lambda var1, var2: var1 + var2
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

( proc (var1, var2: int): int = var1 + var2 )
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

type MyObject = object  ## Documentation Here, **MarkDown** or *ReSTructuredText*
Enter fullscreen mode Exit fullscreen mode

Comments & DocStrings

Python

# This is a comment

""" This is a DocString, plain-text by default """
Enter fullscreen mode Exit fullscreen mode

Cython

# This is a comment

""" This is a DocString, plain-text by default """
Enter fullscreen mode Exit fullscreen mode

Nim + NimPy

# This is a comment

## This is a Documentation Comment, **MarkDown** or *ReSTructuredText*
Enter fullscreen mode Exit fullscreen mode
  • 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
}
""")

Enter fullscreen mode Exit fullscreen mode
  • Cython doesnt have JSON Types.

Nim + NimPy

import json

var variable = %*{
  "key": "value",
  "other": true
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode
  • 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")
Enter fullscreen mode Exit fullscreen mode

Nim

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

Nim

const content = static_read("file.txt")
Enter fullscreen mode Exit fullscreen mode
  • 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__":
Enter fullscreen mode Exit fullscreen mode

Nim

when is_main_module:
Enter fullscreen mode Exit fullscreen mode
  • 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" .}
Enter fullscreen mode Exit fullscreen mode

Thank you for playing

πŸ‘‘

Oldest comments (3)

Collapse
 
hexrcs profile image
Xiaoru Li

This comparison cheatsheet looks awesome, thanks a lot!

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

Collapse
 
bennyelg profile image
Benny Elgazar

Nim = ❀️

Collapse
 
foxoman profile image
Sultan Al Isaiee

This is amazing.
Thank you