Dynamically add fields to dataclass objects

You could use make_dataclass to create X on the fly: X = make_dataclass(‘X’, [(‘i’, int), (‘s’, str)]) x = X(i=42, s=”text”) asdict(x) # {‘i’: 42, ‘s’: ‘text’} Or as a derived class: @dataclass class X: i: int x = X(i=42) x.__class__ = make_dataclass(‘Y’, fields=[(‘s’, str)], bases=(X,)) x.s=”text” asdict(x) # {‘i’: 42, ‘s’: ‘text’}

How to convert a “raw” string into a normal string? [duplicate]

If your input value is a str string, use codecs.decode() to convert: import codecs codecs.decode(raw_unicode_string, ‘unicode_escape’) If your input value is a bytes object, you can use the bytes.decode() method: raw_byte_string.decode(‘unicode_escape’) Demo: >>> import codecs >>> codecs.decode(‘\\x89\\n’, ‘unicode_escape’) ‘\x89\n’ >>> b’\\x89\\n’.decode(‘unicode_escape’) ‘\x89\n’ Python 2 byte strings can be decoded with the ‘string_escape’ codec: >>> import … Read more

Python bytes concatenation

If you want to change your byte sequence, you should use a bytearray. It is mutable and has the .append method: >>> a = bytearray(b’\x14\xf6′) >>> a.append(a[0]) >>> a bytearray(b’\x14\xf6\x14′) What happens in your approach: when you do a += a[0] you are trying to add an integer to a bytes object. That doesn’t make … Read more

pytest and Failed: Database access not allowed, use the “django_db” mark, or the “db” or “transactional_db” fixtures to enable it

Solution: import pytest @pytest.mark.django_db class TestExample: def test_one(): … Assume that you’ve created a TestExample class inside your test file and it should be decorated with @pytest.mark.django_db. It should solve your problem.

Ubuntu: pip not working with python3.4

You have pip installed for python 2, but not python 3. Ubuntu distributes python-pip, python3-pip, python-setuptools and python3-setuptools packages, which you can install (apt-get install etc) as necessary. Thereafter, note that pip installs for python 2, and pip3 installs for python 3 (similar to python, and python3). Setuptools could be said to provide python’s “build” … Read more

TypeError: Object of type bool_ is not JSON serializable

It’s likely because of this issue (or something similar): import numpy as np import json json.dumps({“X”: np.int32(5) > 5}) TypeError: Object of type ‘bool_’ is not JSON serializable The issue is that you end up with something of type bool_ instead of bool. Calling bool()on whichever value(s) are of the wrong type will fix your … Read more

Python SyntaxError: invalid syntax end=”

It seems like you’re using Python 2.x, not Python 3.x. Check your python version: >>> import sys >>> sys.version ‘2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]’ >>> print(1, end=”) File “<stdin>”, line 1 print(1, end=”) ^ SyntaxError: invalid syntax In Python 3.x, it should not raise Syntax Error: >>> import sys … Read more