Attempting to run json.dumps() on a custom class results in the error: “Object of type is not JSON serializable.” By returning the dict as the serializer in a lambda passed to the default parameter of json.dumps(), we can get the class to serialize to JSON.
import json
class Object:
def __str__(self):
return json.dumps(
self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=2)
def __repr__(self):
self.__str__()
# Even better
from dataclasses import dataclass
import orjson
@dataclass()
class Car:
def __init__(self):
self.wheel_count = 4
c1 = Car()
print( orjson.dumps(c1).decode('utf-8') ) # Returns {"wheel_count":4}
$ python3 Python 3.12.3 (main, May 22 2024, 17:31:33) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> arr1 = [1, 2, 3] >>> arr2 = [2, 3, 5] >>> for x in arr1: ... for y in arr2: ... if x == y: ... print(str(x) + ' is in both arrays') ... 2 is in both arrays 3 is in both arrays >>> from itertools import product >>> arr1 = [1, 2, 3] >>> arr2 = [2, 3, 5] >>> for x, y in list(product(arr1, arr2)): ... if x == y: ... print(str(x) + ' is in both arrays') ... 2 is in both arrays 3 is in both arrays
$ python3
Python 3.12.3 (main, May 22 2024, 17:31:33) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Nitin"
>>> age = 40
>>> 'Name: %s ; Age: %d' % (name, age)
'Name: Nitin ; Age: 40'
>>> f'Name: {name} ; Age: {age}'
'Name: Nitin ; Age: 40'
>>> 'Name: %{name}s ; Age: %{age}d' % {'name': name, 'age': age}
'Name: Nitin ; Age: 40'
>>> 'Name: {name} ; Age: {age}'.format(name=name, age=age)
'Name: Nitin ; Age: 40'
>>> from string import Template
>>> tpl = Template('Name: $name ; Age: $age')
>>> tpl.substitute(name=name, age=age)
'Name: Nitin ; Age: 40'
With f-strings, in-line arithmetic is also possible.
uv venv --python 3.14.3