Skip to content

Instantly share code, notes, and snippets.

@OleksiyRudenko
Last active August 10, 2020 17:12
Show Gist options
  • Save OleksiyRudenko/f48e5624c584a0cc4bf7c55636948f29 to your computer and use it in GitHub Desktop.
Save OleksiyRudenko/f48e5624c584a0cc4bf7c55636948f29 to your computer and use it in GitHub Desktop.
Python for JS dev

This cheatsheet is focused more on discrepancies between languages. I.e. you won't find explanation of e.g. * (multiplication) operator as it has exactly same semantics in both languages.

Explanations are given as code examples.

The cheatsheet is also structured rather in a way 'how to read Python code' than 'how to translate some JS into Python'.

Operation Python Better Python JavaScript
Basics
Inline comment # comment // comment
Docstring ''' Function single docstring, make sure to indent ''' """ /**
Miltiline docstring after fn definition. Multiline JSDoc string.
Make sure to indent as fn body code Normally aligned with fn definition line
""" */
Integer division -8//5 == -2 Math.floor(a/b)
String concat + space 'A' 'b' == 'Ab'
Template string '{} {} {}'.format(name, age, age*12) f'{name} {age} {age*12}' `${name} ${age} ${age*12}`
No op when any statement required pass { } // empty block
Map array dest = [x*2 for x in source] const dest = source.map(x => x * 2)
Map array dest = [x*2 if x % 2 else x * 3 for x in source] const dest = source.map(x => x % 2 ? x * 2 : x * 3)
Filter array dest = [x if x % 2 for x in source] const dest = source.filter(x => x % 2)
Filter/map array dest = [x*2 if x % 2 for x in source] const dest = source.filter(x => x % 2).map(x => x * 2)
Exceptions handling try: except Exception as e: else: finally: try {} catch(e) {} finally {} // no 'else' block substitution
Exception invocation raise throw new Exception()

Iterators

sq_list = [x**2 for x in range(10)]  # this produces a list of squares
sq_iterator = (x**2 for x in range(10))  # this produces an iterator of squares

Working with files

with open(file_path, rw_options) as f:
    file_data = f.read(bytes_to_read) # or readline()
    # f.close() is done automatically
    
lines = []
with open(file_path, rw_options) as f:
    for line in f:
        lines.append(line.strip())

Modules

if __name__ == "__main__":
    main()
    
def main():
    # executable code, e.g. tests
import module as m
import module.submodule
from module import object1, object2
from module import object1 as o1
from module import * # anti-pattern

Libraries

See https://pymotw.com/3/

  • csv: very convenient for reading and writing csv files

  • collections: useful extensions of the usual data types including OrderedDict, defaultdict and namedtuple

  • random: generates pseudo-random numbers, shuffles sequences randomly and chooses random items

  • string: more functions on strings. This module also contains useful collections of letters like string.digits (a string containing all characters which are valid digits).

  • re: pattern-matching in strings via regular expressions

  • math: some standard mathematical functions

  • os: interacting with operating systems

  • os.path: submodule of os for manipulating path names

  • sys: work directly with the Python interpreter

  • json: good for reading and writing json files (good for web work)

  • IPython - A better interactive Python interpreter

  • requests - Provides easy to use methods to make web requests. Useful for accessing web APIs.

  • Flask - a lightweight framework for making web applications and APIs.

  • Django - A more featureful framework for making web applications. Django is particularly good for designing complex, content heavy, web applications.

  • Beautiful Soup - Used to parse HTML and extract information from it. Great for web scraping.

  • pytest - extends Python's builtin assertions and unittest module.

  • PyYAML - For reading and writing YAML files.

  • NumPy - The fundamental package for scientific computing with Python. It contains among other things a powerful N-dimensional array object and useful linear algebra capabilities.

  • pandas - A library containing high-performance, data structures and data analysis tools. In particular, pandas provides dataframes!

  • matplotlib - a 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments.

  • ggplot - Another 2D plotting library, based on R's ggplot2 library.

  • Pillow - The Python Imaging Library adds image processing capabilities to your Python interpreter.

  • pyglet - A cross-platform application framework intended for game development.

  • Pygame - A set of Python modules designed for writing games.

  • pytz - World Timezone Definitions for Python

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