How to change a variable by reference like Pandas inplace

172 Views Asked by At

So I was working with Pandas and I recently came across the inplace argument, which changes the original variable without having to reassign it.

Example : df.dropna(inplace=True) instead of df = df.dropna()

I want to apply the same mechanism but for custom functions. However only the list type is natively supported

def append(x, element):
    x.append(element)
x = [1, 2, 3, 4]
append(x, 5)
x
[1, 2, 3, 4, 5]

if I try this with a different type, it does not work

def to_lower(text):
    text.lower()
text = 'Hello World'
to_lower(text)
text
'Hello World'

Does anyone know how Pandas inplace does the job ?

1

There are 1 best solutions below

1
On

I think inplace=True vs inplace=False is achievable at a class level with proper definition of a __repr__ method:

class ToLower:

    def __init__(self, text: str):
        self.text = text

    def to_lower(self, inplace: bool):
        self.text = self.text.lower()
        if not inplace:
            return self

    def __repr__(self):
        return f"{self.text}"

# not in place
example = ToLower("Hello World!")
print("Input value NOT in place :", example)
out = example.to_lower(inplace=False)
print("Input value after NOT in place:", example)
print("Returned after NOT in place:", out)
# update in place
example = ToLower("Hello World!")
print("Input value in place:", example)
out = example.to_lower(inplace=True)
print("Input value after in place:", example)
print("Returned after in place:", out)
text = "LET'S TRY ONE MORE TIME"
example = ToLower(text)
example.to_lower(inplace=True)
print("Desired output:", example)

Input value NOT in place : Hello World!
Input value after NOT in place: hello world!
Returned after NOT in place: hello world!
Input value in place: Hello World!
Input value after in place: hello world!
Returned after in place: None
Desired output: let's try one more time