Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the … Read more

How to print like printf in Python3?

In Python2, print was a keyword which introduced a statement: In Python3, print is a function which may be invoked: In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side. So, your … Read more

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header ‘application/json’ for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header. See more about the jsonify() function here for full reference. Edit: Also, I’ve noticed … Read more

Convert Python dict into a dataframe

The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/… i.e. have multiple columns): You could take the items from the dictionary (i.e. the key-value pairs): But I think it makes more sense to pass the Series constructor:

Purpose of __repr__ method?

__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__ is more for developers while __str__ is for end users. A simple example:

What is print(f”…”)

The f means Formatted string literals and it’s new in Python 3.6. A formatted string literal or f-string is a string literal that is prefixed with ‘f’ or ‘F’. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are … Read more