You are on page 1of 12

Python for JS devs

1. Importing Modules:
In JavaScript, components are imported as such:

import Component from 'reflex/components/component';

On the other hand, in Python, the import statement looks something like this:

from reflex.components.component import Component

In Python, from ... import ... is a more specific version of JavaScript's import
statement. This acts as if you're selectively importing a subset of a module or library.

2. Variables:
Unlike JavaScript, Python does not use const or let for variable declaration. A variable
can simply be declared this way:

initial_nodes = [ ... ]

3. Typing:
Python allows us to give hints about what type of data a variable can hold. It's like
saying, "this bucket can only hold apples" instead of "this bucket can hold any fruit."
Python's dynamic typing system determines the variable type automatically, removing
the need for explicit type declaration during initialization. However, Python developers
often provide type hints for better code readability and maintainability.
However, in NextPy, we have incorporated a stricter type system, similar to TypeScript,
which does enforce these types. Consider the following code:
Example:

Python for JS devs 1


scene: Var[str] = "<https://prod.spline.design/Br2ec3WwuRGxEuij/scene.splinecode>"

Here, scene is like a bucket that is expected to only hold strings ( str ), and right now it
holds a specific web address.

from typing import Any, Dict, List, Union

The above imports type hints. It’s similar to TypeScript in JavaScript. In the code, you
see things like:

nodes: Var[List[Dict[str, Any]]]

This means nodes is expected to be a list of dictionaries where the key is a string and
the value can be any type.

Class Definitions:
In Python, a class is like a blueprint or a template for creating objects. Think of a class
as a sketch of a house, and an object made from that class would be an actual house
built from that sketch.
Example:

class ColorPicker(rx.Component):

This reads as: "I want to define a new mold (or blueprint) called ColorPicker . This new
mold is based on (or inherits from) another blueprint called rx.Component

In JavaScript, class definitions might look like:

class MyClass {
constructor(param) {
this.myParam = param;
}
}

Python for JS devs 2


In Python:

class MyClass:
def __init__(self, param):
self.myParam = param

The def __init__(self, ...): is like the constructor in JS. The self refers to the
instance of the object, like this in JavaScript.

4. Attributes in Classes:
Attributes (sometimes called properties) are like variables inside a class. They store
information that the class needs.

Example:

library = "react-colorful"
tag = "HexColorPicker"

Imagine you're describing a house. The number of bedrooms, color, and type of roof
can be its attributes. Here, the ColorPicker house has a library attribute that is set to
"react-colorful" , and a tag that's set to "HexColorPicker" .

5. Inheritance:
Remember the house blueprint analogy? Let's say you have a basic blueprint for a
building. Now, if you want to design a house, instead of starting from scratch, you can
use the building blueprint as a base and just add house-specific features. This concept
is called inheritance.
Example:

class Spline(rx.Component):

Here, Spline is a new blueprint, but instead of starting from zero, it's based on the
rx.Component blueprint.
The class ReactFlow inherits from ReactFlowLib :

Python for JS devs 3


class ReactFlow(ReactFlowLib):

This is similar to extends in JavaScript.

6. Functions, and Methods:


Functions in Python are defined with def :

def my_function(param):
return param + 2

This is similar to:

function myFunction(param) {
return param + 2;
}

Methods are functions that belong to a class. If attributes are like the number of
bedrooms or color of a house, methods are actions you can do with the house, like
opening a door or cleaning a room.

Example:

def get_event_triggers(self) -> dict[str, Any]:

This is a method named get_event_triggers . The self is a typical convention in Python;


it refers to the instance of the class itself.

7. Dictionaries:
In Python, dictionaries function much like their namesake in the real world. In a physical
dictionary, you have a word (referred to as the "key") which corresponds to its definition
(or "value"). Similarly, Python dictionaries consist of key-value pairs.

For instance:

Python for JS devs 4


return {
**super().get_event_triggers(),
"on_change": lambda e0: [e0],
}

In the code snippet above, we're returning a dictionary. The "on_change" is the key, and
the function lambda e0: [e0] serves as its value.

8.Lambda Functions
Lambdas in Python are concise, unnamed functions:

"on_change": lambda e0: [e0]

This lambda accepts e0 and returns a list containing e0 .

9.Iterating and Conditional Logic


Looping through data structures and implementing conditionals in Python are
conceptually similar to JavaScript but with distinct syntax.

10.Super Function
In Object-Oriented Programming (OOP), a common practice is to create a "base" or
"parent" class that contains general methods. These methods can be reused by other
"child" or "derived" classes without rewriting the same code. The child class can inherit
all the methods from its parent but can also have additional methods or even modify the
inherited ones.

Understanding the Need for super() through an Example:


Let's take a basic example where we have a parent class Vehicle and a child class
Car :

class Vehicle:
def __init__(self, color):
self.color = color

Python for JS devs 5


def start(self):
return "The vehicle starts."

Now, let's say we create a child class called Car which inherits from the Vehicle class:

class Car(Vehicle):
def __init__(self, color, brand):
self.brand = brand
Vehicle.__init__(self, color)

def start(self):
original_message = Vehicle.start(self)
return original_message + " It's a " + self.brand + " car!"

In this example, the Car class is a derived class, and it inherits properties and methods
from the Vehicle class. We're using the Vehicle 's __init__ method to set the color and
the Vehicle 's start method to get the starting behavior.

However, there's a more elegant way to achieve this, and that's where super() comes
in. Using super() , we can avoid directly naming the parent class, which can be
especially useful if you change the parent class's name later or work in multiple
inheritance scenarios.
Here's how we can rewrite the Car class using super() :

class Car(Vehicle):
def __init__(self, color, brand):
super().__init__(color)
self.brand = brand

def start(self):
original_message = super().start()
return original_message + " It's a " + self.brand + " car!"

Notice how cleaner and more concise this is. We've replaced Vehicle.__init__(self,
color) with super().__init__(color) and Vehicle.start(self) with super().start() .

Why is this useful?


1. Flexibility: By using super() , you don't hardcode the parent class name in the child
class. If the name of the base class changes or if the inheritance chain is modified,

Python for JS devs 6


your code will still work without changes.

2. Maintainability: It makes the code more maintainable and readable.

3. Multiple Inheritance: In advanced scenarios where a class might inherit from


multiple parent classes, super() helps in determining the method resolution order.

The super() function in Python provides a way for derived classes to access and build
upon the methods and attributes of their parent class, promoting code reusability and
maintainability.

11.Docstrings
Docstrings in Python offer insights about the code's purpose and usage:

"""A component that wraps a plotly lib."""

They are usually enclosed in triple double quotes and placed at the beginning of the
defined class, method, or function.

Pythonic Thinking
Both languages, while being high-level and interpreted, offer different philosophies and
idioms. Let's explore these differences and help JavaScript developers think more
"Pythonically."

1. Embrace the Zen of Python:

Python for JS devs 7


Python developers often reference the "Zen of Python," a set of aphorisms that capture
the philosophy of the Python language. By typing import this in the Python REPL, you
can view these principles. Two notable aphorisms are:

"Readability counts."

In JavaScript, especially with ES6 syntax, it's common to see concise one-
liners, arrow functions, and other terse structures. While these can be efficient
and elegant, Python places a strong emphasis on code readability. This often
means choosing clarity over brevity.

"There should be one—and preferably only one—obvious way to do it."

Unlike JavaScript, where there can be multiple libraries or methods to achieve


the same goal (think callbacks, promises, async/await for async operations),
Python often encourages a single idiomatic way to accomplish tasks. This
reduces confusion and enhances the uniformity of codebases.

JavaScript:

// Using ES6 to create a concise one-liner to filter even numbers


const evens = arr => arr.filter(num => num % 2 === 0);

Python:

# A more readable approach to filter even numbers


def filter_evens(arr):

Python for JS devs 8


return [num for num in arr if num % 2 == 0]

2. Embrace Indentation and Whitespace:


JavaScript developers might be used to relying on curly braces { } to define code
blocks. In Python, indentation (typically four spaces) itself defines the scope. This might
seem odd at first, but it enforces a consistent, readable style across all Python code.

JavaScript:

if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is 10 or less");
}

Python:

if x > 10:
print("x is greater than 10")
else:
print("x is 10 or less")

3. Dynamic Typing, Yet Differently:


Both JavaScript and Python are dynamically typed languages, but they handle variables
and type coercion differently.

In JavaScript: It's common to rely on type coercion, where the interpreter


automatically changes the type of a variable based on the context. This can
sometimes lead to unexpected results, like "5" + 3 resulting in the string "53" .

In Python: Python is more explicit about type conversion. For example, trying to
concatenate a string with a number directly will raise an error. Developers must
manually convert types when necessary, fostering more predictable code.

JavaScript:

Python for JS devs 9


let result = "5" + 3; // "53"

Python:

# This would raise an error


result = "5" + 3

# Correct way:
result = "5" + str(3)

4. Dive Deep, Not Wide:


While JavaScript, especially in the context of Node.js, has a vast ecosystem of libraries
for every conceivable purpose (thanks to npm), Python encourages diving deeper into
its rich standard library. Before reaching for an external package, it's beneficial to
explore Python's built-in modules, which are comprehensive and optimized.

JavaScript:

// Using lodash library for a simple operation


const _ = require('lodash');
let array = [1, 2, 3];
let reversed = _.reverse(array);

Python:

# Using Python's built-in functionality


array = [1, 2, 3]
reversed_array = array[::-1]

5. Understand Synchronous by Default:


JavaScript developers, especially those working with Node.js or modern frontend
frameworks, are deeply familiar with asynchronous programming. Python, by default, is
synchronous. While Python has introduced asynchronous features with asyncio , many

Python for JS devs 10


of its operations, including I/O-bound tasks, run synchronously. It's essential to
understand this distinction to prevent potential performance pitfalls.

JavaScript (Node.js):

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

Python:

# Synchronous file reading


with open('example.txt', 'r') as file:
data = file.read()
print(data)

6. Think in Comprehensions and Generators:


Python offers powerful constructs like list comprehensions and generators that can
transform the way you think about iterations and data transformations. Instead of
mapping and reducing, as you might in JavaScript, you can often achieve the same
results in Python with a more readable one-liner.

JavaScript:

let numbers = [1, 2, 3, 4, 5];


let squares = numbers.map(num => num * num);

Python:

numbers = [1, 2, 3, 4, 5]
squares = [num * num for num in numbers]

Python for JS devs 11


Python for JS devs 12

You might also like