Home > Net >  assign function w/multiple parameters to a variable —both inside a Python class
assign function w/multiple parameters to a variable —both inside a Python class

Time:12-22

While my code works, I'd like to clean it a bit.
I've built a couple of functions based on thethe File().trashUntrash method, and I've done the same for other methods in the class I'm working on:

class File():
    def__init__(self):
        self.this = this
        self.that = that


    def trashUntrash(self, fileId, bool):
        return file.update(fileId, isTrashed=bool)

    #these two are wrappers for self.trashUntrash:
    trash   = lambda self, fileId: self.trashUntrash(fileId, True)
    untrash   = lambda self, fileId: self.trashUntrash(fileId, False)

    #these other lambdas correspond to other methods:
    fileTitle = lambda self, id: self.fileInfo(prop="title", spreadsheetId=id)                      
    fileIds =  lambda self, id: self.fileInfo(prop="fileId", spreadsheetId=id)
    addPage = lambda self, id, title: self.action(i=0, ssId=id, title=title)
    delPage = lambda self, id, pageId: self.action(i=1, ssId=id, pageId=pageId)
    renameFile = lambda self, id, pageId, title: self.action(i=2, id=id ...)

So I tried assigning the method to variables that I'd then use in the rest of my code:

    trash = self.trashUntrash(fileId, True)
    untrash = self.trashUntrash(fileId, False)
    # and so on...

... as it looks shorter and more easily readable (my goal). But... I get NameError: name 'self' is not defined. Removing self (which of course, doesn't make sense):

    trash = self.trashUntrash(fileId, True)
    untrash = self.trashUntrash(fileId, False)
    # etc.

... will on the other hand, produce NameError: name 'fileId' is not defined. If on the other hand, I simply state:

    trash = self.trashUntrash
    untrash = self.trashUntrash
    # etc... doing this one DOES work BUT 
    # w/o a chance to pass params, which defeats my intent.

... I'll get no errors, but I'll have to manually pass args, including the ones I'm using as default, making the function-to-variable assignment pointless.

So my question: Is it possible to assign a method along with its params to a variable inside a class, and how would you do it?

BTW, I'm using Python 3.10.8 (Nov 1 2022, GCC 12.2.0 on Linux); thank you in advance!

I've already gotten the job done via lambda functions; however, they get quite lengthy as I'm using multiple positional and keyword args. I'd like a way to make these assignments shorter to read.

CodePudding user response:

In the class use partialmethod to define your shortcut. If a further shortcut is needed you can assign the partial method to a local variable:

from functools import partialmethod

class File():
    def trash_untrash(self, file_id, is_trashed):
        print(f"{file_id = }, {is_trashed = }")
        
    trash = partialmethod(trash_untrash, is_trashed=True)
    
f = File()

f.trash(file_id=10)

trash = f.trash
trash(file_id=10)

Output:

file_id = 10, is_trashed = True
file_id = 10, is_trashed = True

CodePudding user response:

Yes, it is possible to assign a method along with its parameters to a variable inside a class. You can do this using a method reference. A method reference is a way to refer to a method without calling it. It is created by prefixing the method name with the object or class name followed by '.'

For example, you can assign the trashUntrash method to a variable trash like this:

trash = File.trashUntrash

Then, you can call the trash variable with an instance of the File class and the arguments you want to pass to the trashUntrash method, like this:

f = File()
trash(f, fileId, True)

Please remember that when you use a method reference, you'll need to pass the instance of the class as the first argument when you call the method.

You can also use the partial function from the functools module to create a function that has some of its arguments fixed. This can be useful if you want to use the same method with the same set of arguments multiple times

For example:

from functools import partial

trash = partial(File.trashUntrash, bool=True)
untrash = partial(File.trashUntrash, bool=False)

f = File()
trash(f, fileId)
untrash(f, fileId)

This way, you can assign the trashUntrash method to the trash and untrash variables with the bool argument fixed to 'True' and 'False', respectively. Then, you can call the 'trash' and 'untrash' functions with the 'File' instance and the 'fileId' argument.

!Please note this answer was generated by ChatGPT

  • Related