Skip to content

Porting JavaScript to Python

Nick Chapman edited this page Jan 19, 2018 · 6 revisions

Porting JavaScript to Python

JavaScript and Python aren't exactly the same, but they're also not that different so transitioning ideas between the two isn't that difficult.

Project structure

To start we are attempting to mirror the existing JavaScript codebase as closely as we can. This is done so that users can switch between the two seamlessly.

Filenames

All file names with a - (hyphen or dash, call it what you will) should be converted to use an _ (underscore), as Python does not allow module names with - (hyphen/dash) in them.

Python Version

This is a Python 3.6 project. Pull requests containing Python 2 code will be rejected. Please make sure you are using the correct version of Python.

Types

Python is a dynamically-typed and strongly-typed language. This is great for a number of reasons, but it can also make navigating large codebases confusing as it is frequently unclear what the types of arguments and variables are. To help with this Python 3.5 intdroduced type hinting. To the best of our ability this project aims to provide type hints wherever possible.

Class Variable Names

Variables that are private in the original codebase should be prefixed with an _ (underscore) in the Python codebase. Public variables should have no underscore. Example:

Original JavaScript
-------------------
public aVariable
private someVariable

New Python
-------------------
aVariable
_someVariable

Python vs JavaScript Method Names

There are some code formatting rules in Python that are different from JavaScript. For this project the most notable will likely be the difference in method names:

JavaScript (well really TypeScript)
----------

public getSomething() {
    // Do something here
}

==============================================================

Python
----------

def get_something():
    # Do something here

Python uses snake case while all of the existing Request code is in camel case. For now we are going to keep the camel case names to speed the process of porting over code. At a later date and time we will refactor all of the method names to become PEP-8 compliant.

Argument Names

In the original JavaScript a lot of the argument names are prefixed with an _ (underscore). The Python arguments drop the _ (underscore). Example:

Original JavaScript
-------------------
public someMethod(_argument)

New Python
-------------------
def someMethod(argument)

Optional arguments

Optional arguments in the JavaScript methods should be carried over to Python as default None key word arguments. Example

Original JavaScript
-------------------
public static init(web3Provider ?: any, networkId ?: number)

New Python
-------------------
@staticmethod
def init(web3Provider: Any=None, networkId: int=None)