views:

265

answers:

3

Hey,

My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm following convention.

__str__ is supposed to be informal and concice, so I've made it return the bit field's decimal value (i.e. str(bit field 11) would be "3".

__repr__ is supposed to be a official representation of the object, so I've made it return the actual bit string (i.e. repr(bit field 11) would be "11").

In your opinion would this implementation meet the conventions for str and repr?

Additionally, I have used the bin() function to get the bit string of the value stored in the class. This isn't compatible with Python < 2.6, is there an alternative method?

Cheers,

Pete

+1  A: 

I'd consider having __str__ return a hexadecimal representation instead. This way, it's easier to eyeball what the actual bit values are, and thus more useful. But still quite concise (in fact, fewer characters than the decimal representation).

sblom
+11  A: 

The __repr__ should preferably be a string that could be used to recreate the object, for example if you use eval on it - see the docs here. This isn't an exact science, as it can depend on how the user of your module imported it, for example.

I would have the __str__ return the binary string, and the __repr__ return Classname(binary_string), or whatever could be used to recreate the object.

In the bitstring module (which I maintain) the __str__ is hexadecimal if the bitstring is a multiple of 4 bits long, otherwise it's either binary or a combination of the two. Also if the bitstring is very long then it gets truncated (you don't want to try to print a 100 MB bitstring in an interactive session!)

I'd avoid using the bin() function altogether if I were you. The reason being that it can't be used if your bitstring starts with zero bits (see my question here). I'd advise using either use a bin method or property instead.

Scott Griffiths
Agreed. I think as a rule eval(repr(x)) should re-create x as well as possible. not sure about str, but i like this solution.
Claudiu
A: 

__repr__ needs to return something that, if passed to your constructor, would create a new object that is an identical copy of the original one.

Yours returns '11' but if you passed '11' to your constructor you would not get the same bitfield as a result. So this __repr__ is not ok.

joefis