Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit wise modification of integers in Python

The program I'm writing manipulates integers by applying binary operations to them (e.g. >>, &, |). Many of the operations are applied inside functions, and to make the results of the operations persist once the function returns, I'm returning a copy of the altered variable.

Something like:

updated = applyOp(original, amnt)

def applyOp(original, amnt):
    return original >> amnt

If I didn't want to return a copy of the integer and instead wanted the changes made to original within the function to persist outside of the function, I suppose I could create a wrapper class of some kind. Are there other options? Perhaps ones that specifically facilitate bit wise integer manipulation?

like image 887
Adam Avatar asked Mar 04 '26 02:03

Adam


1 Answers

In Python, assignment to a variable changes the variable binding rather than the value at a particular memory location. In order to allow modification in the way that you are describing, I believe you will need to change stored data rather than a variable binding. Take the following example:

a = 1
b = a
a = 2

Because assignment changes the variable binding, a is now bound to 2, but b is still bound to 1. You really want the opposite behavior, but (to my knowledge) this behavior is not available in Python.

As you correctly say, this will require some sort of a wrapper. However, a class for this purpose isn't strictly necessary. One of the easiest ways to accomplish this is by putting your data in a list. Take this example:

a = [1]
b = a
a[0] = 2

Now, a and b still contain the same list (since no reassignment was made to either), and so a[0] == b[0] == 2. So one valid solution is to always pass a single-item list to the function rather than directly passing the value.

Another answer might be to share data between functions by making them both methods of the same class, which of course can share member variables. However, I cannot tell from your limited information if this approach is appropriate for you.

Here is an example of how this could potentially work:

class MyClass:
    def __init__(self):
        self._value = 0;

    def do_something(self):
        # Do something with self._value
        self._helper_function()
        # Continue using self._value

    def _helper_function(self):
        # No need to pass the value in. It is accessible at self._value

Again, whether or not this would work depends on exactly what you are trying to do.

like image 122
bytesized Avatar answered Mar 06 '26 16:03

bytesized



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!