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 ?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With