Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Learning Python as a JS Developer

Python and JS are the two most popular programming languages. I was working as a MEAN/MERN Stack Software Engineer where I used Javascript as a coding Language. Recently I switched to Python for a second project.

In this blog, I will share my experience of working on both languages at the same time. Let’s get started.

Below are the code snippets which describe the major syntax differences. Can you observe how different they are?

A sample code block in Python

# Comments in python by using '#'

print("Hello folks, This is to debug the error!!")

def functionSyntaxInPython():
    func_syntax = 'Use def keyword in start and use : in end'
    return func_syntax

# If/else block in python
if 'def' in func_syntax and ':' in func_syntax:
    return 'function is in python syntax'
else:
    return 'function not in python syntax'

class class_in_python:
    def __init__(self, name, age):
        self.current_function_is = 'constructor'
        self.default_arg = 'self which work as this'
    
    def class_method(self):
        print("This is python class method")

# Creating object and calling method in python
python_obj = class_in_python()
python_obj.class_method()

A sample code block in Javascript

// Comments in javascript using '//'

console.log("Hello folks, This is to debug the error!!")

function functionSyntaxInJS(){
    var func_syntax = 'Use function keyword in start and use { in end'
    return func_syntax
}

// if/else block in JS
if (func_syntax.includes('{')) {
    return 'function is in js syntax'
} else {
    return 'function is not in js syntax'
}

class classInJS(){
    constructor() {
        this.current_function_is = 'constructor';
    }
    class_method() {
        console.log("This is JS class method")
    }
}

// Creating class object and call its class class method
js_obj = new classInJS()
js_obj.class_method()

The syntax b/w Javascript and Python are very different as shown in the above sample blocks. Sometimes I make mistakes by using one’s syntax in another. To avoid this these IDE’s are really helpful– IntelliJ (Python) and Vscode (Javascript).

Below are the major differences that I came across:-

  1. Python code uses tabs for a code block whereas JS uses { }
  2. Python uses ‘#’ for comment while JS use ‘//’
  3. Python uses the ‘print’ keyword whereas JS uses ‘console’ keyword to debug anything in the console panel.
  4. Python Function uses a ‘def’ keyword to define function whereas JS uses ‘function’ keyword
  5. The constructor of the Python class is defined by ‘__init__’ whereas JS uses a normal constructor.
  6. The semicolon is not mandatory in both languages to define the end of a statement. But we use it in JS because if we don’t apply it, JS engine will apply it automatically and create unnecessary bugs in the code.

Approaches to implement task in different languages

Every language has its own beauty. While solving any task with NodeJS I need to think in a different way than implementing them in Python. In some scenarios, Python wins and in some NodeJS.

Just a small example-

To create a Task manager backend in NodeJS, I need to use Express. To replicate the same functionality in Python, I need to use Flask.

Checkout repo for basic task manager https://github.com/agarwalparas/task-manager

However, later on, if my backend needs a functionality of Machine learning to manage tasks and prioritize them on the basis of users’ behaviour, then I will surely use Python.

Whereas if my backend needs high speed to list tasks or to search from tasks or for faster real time updates of tasks within the team, then I will surely use NodeJS.

So, it is really tough to decide which language to use in which project. But it is fairly straightforward to say which language can be used for a particular task.

After some experience, I have figured out a way to decide which language is better for a project.

NodeJS for Chat Applications and Realtime Apps whereas Python for Analytics, Machine Learning, Command Line Utilities.

Some important concepts

F String in Python and Template literals in Javascript

The F string and template literals are great new ways to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, they are also faster!

# Example of F string in python

name  = 'Gaurav'
print(f"It is nice meeting with you {name}")
# Response -> It is nice meeting with you Gaurav

// Example of template literal in JS
let name = 'Gaurav'
console.log(`It is nice meeting with you ${name}`)
// Response -> It is nice meeting with you Gaurav

Decorators in Python and Callback Function in Javascript

Decorators and Callback Function are very powerful and useful tools since they allow programmers to modify the behavior of function or class. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function whereas in Javascript the function passed as argument is called callback function.

# Decorators In Python
# Here we create a uppercase decorator that takes a function as a argument
def decorator_for_uppercase(function):
    def wrapper():
        func = function()
        make_uppercase = func.upper()
        return make_uppercase
    return wrapper

def print_hi():
    return 'hello there'
  
# Here we call the uppercase decorator by passing a function as a argument 
decorate = decorator_for_uppercase(print_hi)
decorate()

# Instead of previous function definition we can also define decorator using '@' in python
@decorator_for_uppercase
def print_hi():
    return 'hello there'
print_hi()

// Callbacks In JS
// Here we pass callback function inside a fn as an argument
function download_image(picture_url, callback) {
    setTimeout(() => {
        // Code to download image here
        console.log(`Downloading ${picture_url} ...`);
        
        // process the image once it is completed
        callback(url);
    }, 300);
}

// Here i call the function that takes a function as a argument which is basically a callback function
let picture_url = 'https://www.xyz.jpg';
download_picture(picture_url, function(picture) {
    console.log(`Image downloaded ${image}`);
    // Write code here to do anything with the downloaded image
});

Async/Await in NodeJS 

Before async/await, JS used promises but its code was a little complex to debug and caused callback problems.

Then JS introduced a neat syntax to work with promises in a more comfortable fashion. It’s called “async/await” and is relatively easy to understand and use.

Example

// Await can only used inside async function and async function can be created by applying async keyword
async function f() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });
  // await can only used inside async function
  let result = await promise; // wait until the promise resolves (*)
}

// async function always returns a promise
f()

Python doesn’t have any such features but there are libraries in Python which provide these powerful features ie. asyncio

Conclusion

So all in all it’s a very exciting journey. Both languages have some pros and cons. But isn’t it the same with everything. Different languages exist because there is no one-size fits all approach to programming. In fact, their existence gives us tools to help create more robust products. My experience of working with Python and JS simultaneously has helped me gain more exposure to the world of programming languages and I now look forward to learning more about other unknown languages.



This post first appeared on C.R.A.P. Design Principles To Improve Visual Appeal, please read the originial post: here

Share the post

Learning Python as a JS Developer

×

Subscribe to C.r.a.p. Design Principles To Improve Visual Appeal

Get updates delivered right to your inbox!

Thank you for your subscription

×