Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python give *args default value

Inside my class I have:

def refresh(self, func = None, *args):
    if not func:
        return
    new_data = func(*args)
    self.set_text(new_data)

But I have 2 problems:

  1. What if func doesn’t take any parameters? Why can’t I do *args = None?
    like I want to do something like this:

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    def refresh(self, func = None, *args = None):
        if not func:
            return
        if *args:
            new_data = func(*args)
        else:
            new_data = func() # func doesn't take any parameters
        self.set_text(new_data)
    
  2. When I try to run my code before the edits I get:

    TypeError: function takes 0 positional arguments but 1 were given

    Why is that?

Here is my main:

def hello_world():
    return 'hello'

tmp2 = LLabel('Hi There!')
tmp2.refresh(hello_world, None)

>Solution :

None is an argument of NoneType. You can try it simply by running the hello_world function by itself.

def hello_world():
    return 'hello'
hello_world(None)

Which will result in the following error: TypeError: hello_world() takes 0 positional arguments but 1 was given.

Hence run the refresh method, with only one argument – the function you want to pass in:

def hello_world():
    return 'hello'
tmp2 = LLabel('Hi There!')
tmp2.refresh(hello_world)

Therefore the original refresh method can stay the same:

def refresh(self, func = None, *args):
    if not func:
        return
    new_data = func(*args)
    self.set_text(new_data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading