Productivity is the result of a commitment to excellence, intelligent planning, and focused effort.

Python vs JavaScript snippets

Cover Image for Python vs JavaScript snippets
George Crisan
George Crisan
Posted on:

I've started recently to use Python with Scrapy. Naturally, when I need to do certain things like spreading a list of values or using a try/catch block, my brain attempts initially to write code the way we do it in JavaScript. (I've done mainly JavaScript for the last 7 years or so) Assuming you are new to Python too, these snippets are meant to stimulate our brain's neuroplasticity. Enjoy.

Will start with the most basic concepts and will end up with more complex. The code below is ready to run. No pseudo code, copy/paste it in a working environment and should be ready to play with it straight away.

1. Destructuring assignment

This is what I find myself using frequently, in a way or another.

Python

bikes_brands = ['honda', 'yamaha', 'triumph', 'suzuki', 'ducati']

first, second, *others = bikes_brands

print(first, second, others)

# Output: honda yamaha ['triumph', 'suzuki', 'ducati']

JavaScript

const bikeBrands = ['honda', 'yamaha', 'triumph', 'suzuki', 'ducati'];

[first, second, ...others] = bikeBrands;

console.log(first, second, others);

// Output: honda yamaha ['triumph', 'suzuki', 'ducati']

2. Nested ternary operator

Not the best practice but worth mentioning for the sake of the article. Please keep your code easy to read.

Python

age = 32

result = 'George is old' if age > 59 else 'George is young' if age <= 40 else 'George is middle age'

print(result)

# Output: George is young

JavaScript

const age = 32;

const result = age > 59 ? "George is old" : age <= 40 ? "George is young" : "George is middle age";

console.log(result);

// Output: George is young

3. Class and method declaration

Python

Python has the concept of magic method, see the __str__ example


class Bike():
  def __init__(self, brand, capacity):
    self.brand = brand
    self.capacity = capacity
  
  # Magic method
  def __str__(self):
    return f'Bike - brand: {self.brand}, engine capacity: {self.capacity} cc'
    
  #Normal method 
  def toString(self):
    return f'Bike - brand: {self.brand}, engine capacity: {self.capacity} cc'
    
my_bike = Bike('Honda', 600)

# magic method use case 
print(my_bike)  

# standard method use case
print(my_bike.toString()) 

# Output 1: Bike - brand: Honda, engine capacity: 600 cc
# Output 2: Bike - brand: Honda, engine capacity: 600 cc

JavaScript

"this" from JavaScript is not the same as "self" in Python.
There are cirumstances where these two have similar behaviour but "this" has different functionality based on the function invokation context.

class Bike {
    constructor(brand, capacity) {
        this.brand = brand;
        this.capacity = capacity;
    }

    toString() {
        return `Bike - brand: ${this.brand}, engine capacity: ${this.capacity} cc`
    }
}

const myBike = new Bike("Yamaha", 1000);

console.log(myBike.toString())

// Output: Bike - brand: Yamaha, engine capacity: 1000 cc

4. Try, catch and finally block

Python

# Code that could cause exceptions
try:
  print("No problem so far")
  print(x)

# This block executes if an exception of type "NameError" occurs
except NameError:
  print("Variable x is not defined")

# This block executes if other exception occurs
except:
  print("We have a problem")

# Code to run indiscriminately
finally:
  print("I am done")

# Output 1: No problem so far
# Output 2: Variable x is not defined
# Output 3: I am done

JavaScript

try {
  // tryCode - Code block to run
  console.log("no problem so far");
  console.log(undeclaredVariable);
}
catch(error) {
  // catchCode - Code block to handle errors
    console.log("[Error] ", error.message);
}
finally {
  // finallyCode - Code block to be executed regardless of the try result
  console.log("Life is good")
}

/** Output:
 * no problem so far
 * [Error]  undeclaredVariable is not defined
 * Life is good
 */

5. Infinite Generator

Python

def my_generator():
    num = 0
    while True:
        yield num
        num += 1

generator = my_generator();
print(next(generator))
print(next(generator))
print(next(generator))

# Output: 0 1 2

JavaScript

function *myGenerator() {
    let nr = 0;

    while (true) {
        yield nr;
        nr++;
    }
}

const generator = myGenerator();

console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().value);

// Output: 0 1 2

This was a fun article to make. Thank you if you've managed to read so far and have a lovely day.