Alternatives for returning multiple values from a Python function [closed]

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example. >>> import collections >>> Point = collections.namedtuple(‘Point’, [‘x’, ‘y’]) >>> p = Point(1, y=2) >>> p.x, p.y 1 2 >>> p[0], p[1] 1 2 In recent versions of Python 3 (3.6+, I think), the new typing library got … Read more

How to make a class JSON serializable

Here is a simple solution for a simple feature: .toJSON() Method Instead of a JSON serializable class, implement a serializer method: import json class Object: def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) So you just call it to serialize: me = Object() me.name = “Onur” me.age = 35 me.dog = Object() me.dog.name = … Read more

How to deal with SettingWithCopyWarning in Pandas

The SettingWithCopyWarning was created to flag potentially confusing “chained” assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.] df[df[‘A’] > 2][‘B’] = new_val # new_val not set in df The warning offers a suggestion to rewrite as … Read more

How does Python’s super() work with multiple inheritance?

This is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts). In your example, Third() will call First.__init__. Python looks for each attribute in the class’s parents as they are listed left to right. In this case, we are looking for __init__. So, … Read more

How to get the ASCII value of a character

From here: The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick. >>> ord(‘a’) 97 >>> chr(97) ‘a’ >>> chr(ord(‘a’) + 3) ‘d’ >>> In Python 2, there was also the unichr function, returning the Unicode character … Read more