Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else based on existence of python function optional arguments

I have written a function as follows, with optional argument 'b'.

url depends on the existence of b.

def something(a, b=None)
    if len(b) >= 1:
        url = 'http://www.xyz.com/%sand%s' % (a, b)
    else:
        url = 'http://www.xyz.com/%s' (a)

This raises an error when b=None, saying "object of type 'none-type' has no length"

Any ideas how to get around this?

like image 818
snakesNbronies Avatar asked May 12 '12 21:05

snakesNbronies


People also ask

How do you set optional arguments in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

What is optional argument in Python?

A type of argument with a default value is a Python optional parameter. A function definition's assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take.

How can I pass optional or keyword parameters from one function to another?

Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. Without using keyword arguments. By using keyword arguments.

Are function call arguments optional?

So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.


3 Answers

You can try this code:

def something(a, *b):
    if len(b) == 0:
        print('Equivalent to calling: something(a)')
    else:
        print('Both a and b variables are present')
like image 174
Kuruvachan K. George Avatar answered Oct 25 '22 01:10

Kuruvachan K. George


You can simply use if b: - this will require the value to be both not None and not an empty string/list/whatever.

like image 27
ThiefMaster Avatar answered Oct 25 '22 01:10

ThiefMaster


You can simply change -

def something(a, b=None)

to -

def something(a, b="")
like image 34
theharshest Avatar answered Oct 25 '22 02:10

theharshest