Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass boolean values as input to method

How do I pass boolean as argument to a method ?

For example, I have a code as below:

def msg_util(self, auth_type=None,starttls=False):
....
starttls=True
invoke_tls(self, auth_type, auth_value, "require_tls=%s" %starttls)
....
....
def invoke_tls(self, auth_type=None, auth_value=None,range=None,style=None, adminuser=None,require_tls=False):
...

Since am passing starttls as string from invoke_tls method, in the method definition invoke_tls, if require_tls is not set to boolean False by default, starttls is taken as "True" (string)

Please let me know if there is a way I can pass boolean type as optional parameters in python.

I know that one way is to process the string in if else condition and process it as below:

def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
       return True
    elif 'FALSE'.startswith(ua):
       return False

But, please let me know if there is any other effective or better way to pass boolean values as input to another method ?

like image 360
Shankar Guru Avatar asked Dec 28 '16 07:12

Shankar Guru


2 Answers

There's nothing special about True or False values...

invoke_tls(self, auth_type, auth_value, starttls)

If what you mean is how to pass specific parameters but not others, Python has "keyword parameters":

def foo(a, b=1, c=False):
    print(a, b, c)

foo(1)          # b will be 1 and c False (default values)
foo(1, c=True)  # b will be 1 (default) and c True

Python also allows to specify keyword arguments dynamically... for example

parms = {"c" : True}  # Dictionary name → value
foo(1, **parms)       # b will be 1 (default), c will be True
like image 175
6502 Avatar answered Sep 28 '22 06:09

6502


Boolean is a data type and can be passed around as any other data type.

Check:

a = True
def foo(b=None):
    print b
foo(a)

Output:

True
like image 27
Mohammad Yusuf Avatar answered Sep 28 '22 06:09

Mohammad Yusuf