How to make something like PHP in Python. Part 1
How to make stdClass like in PHP
When working with Python, often, out of habit, you want to pull something from other languages. This is not always useful and correct, but…
In PHP you can create an object similar to the dict in Python, but with the ability to access properties through the property access statement. Easier to show:
$mydict = (object) [ # new stdClass
'foo' => 123,
'bar' => fn($x)=> $x + 1
];
$mydict->foo; # = 123
out of habit, I expected to be able to write like this in Python:
mydict = {
'foo': 123,
'bar': lambda x: x + 1
}
mydict.foo # Error
In Python this analogue is implemented as follows:
a = type("stdClass", (), {
"foo": 123,
"bar": lambda x: x + 1
})
print(a.bar(a.foo)) # 124
print(type(a)) # <class 'type'>
In Python, everything is an object, and classes are not an exception, which means that someone creates these classes. In fact, all classes are created by type, which is the base class. Every class has a type, and the type of the class itself is the class itself. This is a recursive closure that is implemented inside Python using C:
type(type) # <class 'type'>
By the way, the second argument in type is a tuple that lists the classes to inherit from:
class B:
buz: "abc"
a = type("stdClass", (B,), {})
print(a.buz) # abc
I will be adding different versions of the code to this repository. If you are interested, please like it and subscribe to updates.