Python For JS Devs
Python For JS Devs
1. Importing Modules:
In JavaScript, components are imported as such:
On the other hand, in Python, the import statement looks something like this:
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:
Here, scene is like a bucket that is expected to only hold strings ( str ), and right now it
holds a specific web address.
The above imports type hints. It’s similar to TypeScript in JavaScript. In the code, you
see things like:
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
class MyClass {
constructor(param) {
this.myParam = param;
}
}
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 :
def my_function(param):
return param + 2
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:
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:
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:
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.
class Vehicle:
def __init__(self, color):
self.color = color
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() .
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:
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."
"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.
JavaScript:
Python:
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")
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:
# Correct way:
result = "5" + str(3)
JavaScript:
Python:
JavaScript (Node.js):
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Python:
JavaScript:
Python:
numbers = [1, 2, 3, 4, 5]
squares = [num * num for num in numbers]