Skip to content

Instantly share code, notes, and snippets.

@dhkatz
Last active February 26, 2019 15:27
Show Gist options
  • Save dhkatz/694336a57fcdcbc08bf4c57b58a0d6c0 to your computer and use it in GitHub Desktop.
Save dhkatz/694336a57fcdcbc08bf4c57b58a0d6c0 to your computer and use it in GitHub Desktop.
Python 3.7+ vs ES2018+ Syntax Comparison

Python 3.7+ vs ES2018+ Syntax Comparison

Introduction

This gist is meant to outline differences in syntax and performing common operations in both Python and Javascript (ES2018). This gist may not cover absolutely everything, so a quick double check with Google or StackOverflow can be a big help.

This gist will not cover the extreme basics of the language (i.e. array indexing) because many of these things are intuitive or just common across most languages.

Many of these newer ES2018+ language features might not be available in all browsers. It’s best to use a transpiler/compiler like Babel or Typescript to generate browser compatible code.

Packages

Package Management

Very similar package management between Python and ES2018 when using pipenv to mimic much of the ease of use of npm. Both of the these solutions support using git repositories as well.

Python

Using pipenv, you can easily create virtual (local) environments that supports a more advanced dependency system. This uses a Pipfileand Pipfile.lock similar to npm’s own package.json and package-lock.json files.

pipenv install # Install from existing Pipfile or create local environment
pipenv install requests # Install a package locally
pipenv uninstall requests # Uninstall
pipenv install git+https://github.com/user/repo@branch#egg=package # Git

Javascript

Javascript has NPM which, in recent years, has gotten better than it already was. NPM by default installs packages locally, which is much preferred by most developers. Many of the security issues with packages and npm itself have been fixed. NPM uses a package.json and package-lock.json for project dependencies.

npm init # Create new local node environment
npm install # Install from existing package.json
npm install request # Install a package locally
npm uninstall request # Uninstall
npm install user/repo#branch # Git support

Imports

Python

import math
print(math.log(42))

from math import log
print(log(42))

# not a good practice (pollutes local scope) :
from math import *
print log(42)

Javascript

import math from 'math';
console.log(math.log(42));

import { log } from 'math';
console.log(log(42));

import * from 'math';
console.log(log(42));

Functions

Basic Functions

Python

def foo():
    pass

def bar(a, b = 1):
    return a * b

Javascript

function foo() {
    
}

function bar(a, b = 1) {
    return a * b;
}

Anonymous Functions

Python

def foo(outer):
    def bar(inner):
        return outer + inner
    return bar

Javascript

function foo(outer) {
    return (inner) => {
        return outer + inner;
    }
}

Asynchronous Functions

Python

Python does not support top-level await

async def foo():
    return await bar()

# Calling the function
result = await foo()

Javascript

ECMAScript does not currently support top-level await but most likely will

async function foo() {
    return await bar();
}

// Calling the function
const result = await foo(); // or foo().then(callback)

Generators

Python

def foo():
    yield 1
    yield 2
    yield 3

Javascript

function *foo() {
    yield 1;
    yield 2;
    yield 3;
}

Lambdas

Python

lambda x: x * 2

Javascript

x => x * 2

Iterators

Python

def fibonacci():
    pre, cur = 0, 1
    while True:
        pre, cur = cur, pre + cur
        yield cur
        
for n in fibonacci():
    if (n > 1000):
        break
	print(n)

Javascript

const fibonacci = {
    [Symbol.iterator]: function *() {
        let pre = 0, cur = 1;
        while (true) {
            [pre, cur] = [cur, cur + pre];
            yield cur;
        }
    }
};

for (const n of fibonacci) {
    if (n > 1000)
        break;
    console.log(n);
}

Object Oriented Programming

Classes

Python

Supports multiple inheritance

class SpiderMan(Human, Superhero):
    def __init__(self, age):
        super(SpiderMan, self).__init__(age)
        self.age = age
    
    def attack(self):
        print('Spider web!')

Javascript

class Spiderman extends Superhero {
    constructor(age) {
        super(age);
        this.age = age;
    }
    
    attack() {
        console.log('Spider web!');
    }
}

Getters and Setters

Python

class Foo:
    @property
    def x(self):
        return self.__x
    
    @x.setter
    def x(self, x):
    	self.__x = x

Javascript

class Foo {
    get x() {
        return this._x;
    }
    
    set x(x) {
        this._x = x;
    }
}

Useful Concepts

Comprehensions

Python

# Array Comprehension
names = [c.name for c in customers if c.admin]

# Dictionary Comprehension
letters = { key: val for key, val in enumerable('ABCD') if val not in 'CB' } 
# { 0: 'A', 3: 'D' }

Javascript

Through supported transpilers/compilers like Babel

// Array Comprehension, not natively supported
const names = [for (c of customers) if (c.admin) c.name];

// Something similar can be acheived natively with generators

const names = [...function *() {
    for (const c of customers) if (c.admin) yield c.name;
}()];

Range Creation

Python

Note that Python’s range() method must be turned into a new list

print(range(5))
# range(0, 5)

print(list(range(5)))
# [0, 1, 2, 3, 4]

Javascript

console.log(Array.from(Array(5).keys()));
// [0, 1, 2, 3, 4]

Destructuring

Python

Python does not support object destructuring.

# Array Destructuring
head, *tail = [1, 2, 3, 4] # head = 1, tail = [2, 3, 4]

a, b = (1, 2) # a = 1, b = 2

# Object "destructuring"
a, b, c = [{ 'a': 1, 'b': 2, 'c': 'Hello!' }[k] for k in ('a', 'b', 'c')]
# a = 1, b = 2, c = 'Hello!'
// Array Destructuring
const [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4]

const [a, b] = [1, 2]; // a = 1, b = 2

// Object Destructuring
const { bar } = { bar: 2 }; // bar = 2

const { a, b, c } = { a: 1, b: 2, c: 'Hello!' }; // a = 1, b = 2, c = 'Hello!'

Spread Operator

Python

# Positional Spread
array = [1, 2, 3]
print(*array) # 1, 2, 3

# Object Spread
obj = { 'a': 2, 'b': 3}

def foo(b, a):
  print(b, a)

foo(**obj) # 3, 2

obj2 = { **obj, 'c': 4 }

Javascript

ECMAScript does not support keyword arguments

// Positional Spread
const array = [1, 2, 3];
console.log(...array); // 1, 2, 3

// Object Spread
const obj = { a: 2, b: 3 };
const obj2 = { ...obj, c: 4 };

Variable Swapping

Python

Swapping is easy by knowing how tuples work in Python

a, b = 1, 2

a, b = b,a 

Javascript

Swapping is easy through array destructuring

const a = 1, b = 2;

[a, b] = [b, a];

Structure Methods and Operations

Array Methods

Python

Many of Python’s built-in iterative functions return iterators and must explicitly be turned into lists

doubles = list(map(lambda x: x * 2, [1, 2, 3, 4])) # [2, 4, 6, 8]

odds = list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4])) # [1, 3]

length = len([1, 2, 3, 4]) # 4

concat = [*[1, 2, 3], *[4, 5, 6]] # [1, 2, 3, 4, 5, 6]

Javascript

const doubles = [1, 2, 3, 4].map(x => x * 2); // [2, 4, 6, 8]

const odds = [1, 2, 3, 4].filter(x => x % 2 == 1); // [1, 3]

const length = [1, 2, 3, 4].length; // 4

const concat = [...[1, 2, 3], ...[4, 5, 6]]; // [1, 2, 3, 4, 5, 6]

String Methods

Python

Python supports the f-string syntax since 3.7+

string = 'Hello'

length = len(string) # 5

template = f'{string} World!' # Hello World!

Javascript

const string = 'Hello';

const length = string.length; // 5

const template = `${string} World!`; // Hello World!

Object/Dictionary Methods

Python

dict = { 'a': 1, 'b': 2, 'c': 3}

keys = dict.keys() # ['a', 'b', 'c']
values = dict.values() # [1, 2, 3]
pairs = dict.items() # [('a', 1), ('b', 2), ('c', 3)]

Javascript

const obj = { a: 1, b: 2, c: 3 };

const keys = Object.keys(obj); // ['a', 'b', 'c']
const values = Object.values(obj); // [1, 2, 3]
const pairs = Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment