Write Python in Javascript Style
Some Javascript practices are good, up to your taste. This article demonstrates some examples how to write Python in the fashion of Javascript.
Dynamic Object
Javascript
var a = {}
a.v = 1
a.f = function() {
console.log('hello')
}
console.log(a.v)
a.f()
Python
class Namespace:
pass
a = Namespace()
a.v = 1
print(a.v)
def hello():
print('hello')
a.f = hello
a.f()
# another object
b = Namespace()
We just need to create an empty class as a class is a namespace and allows you to set attributes.
Note you cannot use a = {}
to achieve the same as js because dict object don't allows you to set attributes (no __setattr__
function).
a = {}
a.v = 1
AttributeError Traceback (most recent call last)
line 2
1 a = {}
----> 2 a.v = 1
AttributeError: 'dict' object has no attribute 'v'