I am trying to skip parameters while calling a function. Could you please help me how to do this?
Example:
I have to call below function which is having 3 parameters:
send_mail(audit_df, LOG_FILE, Duration)
I have to call above function to skip 1st and 3rd parameters. How can i do this?
You can setup default values for the parameters. I don't know what works for you, so I just set them to None.
def send_mail(audit_df=None, log_file=None, duration=None):
do all the things
when calling
send_mail(log_file="myfile")
For a little light reading see the Function definitions section of the docs.
You can place "None" in place of the parameter.
This is going to make python assume that it is Nothing and will do nothing.
This can be done in two ways using
**kwargs
Optional parameters
See the answer below for details
Multiple optional arguments python
Related
I'm just starting to learn Python 3.9 as my first language. I have been fighting with this error for a while now, and I can't figure out what the issue is.
Here's what I'm working on:
def eval_express(eqstring[0], eqstring[1], eqstring[2]):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
I'm receiving an error that the "(" after eval_express is not closed, but as far as I can tell it is. At first, I thought it was just a glitch, but despite numerous attempts to rewrite it, increase/decrease the number of arguments, etc. it persisted. The error cropped up after I modified the arguments from variables to list items, but I don't see why that would affect it. Can anyone provide some clarification on what the program's getting hung up on?
Thank you for your help!
You are using square brackets inside the function parameters, which is not valid. Valid code would be:
def eval_express(eqstring0, eqstring1, eqstring2):
eqstring0, eqstring2 = float(eqstring0), float(eqstring2)
return opdict[eqstring1](eqstring0, eqstring2)
although you should probably use more descriptive parameter names.
You can't use parameter[] notation when entering a parameter to a function. Instead just use parameter, or you will have to do something like.
def eval_express(eqstring):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
Now you have to pass an array as the function parameter.
My code for the above problem statement is:
def firstletter(x):
x=input()
print(x[0])
firstletter()
But I'm getting this error
Oops, your solution is incorrect.
TypeError: firstletter() missing 1 required positional argument: 'x'
can anyone help me with that.
your function isn't taking any parameters at the moment. Below is a link to some documentation that explains what functions and function parameters are.
python functions
The correct answer to this is:
def firstletter(x):
print(x[0])
because the compiler already had custom input it was just checking whether the function had a parameter passed, and one character is taken or not.
p.s.: in udemy we are not able to see if there are test cases or custom inputs.
for example:
#creating the function with params
def symlinks(release_path, deploy_to, settings_file, roll_back=False, is_file=False):
#doing something with all the params
#executing the function
symlinks(releasepath, deploypath, settingsfile, is_file=true)
So there are multiple ways of passing parameters to functions in python, is the above one valid?
i tried symlinks(releasepath,deploypath,True) but seems like it is impacting roll_back.
Would the roll_back param be still false?
Arguably the coolest way for you to find the answer to your question, would be using inspect.getcallargs. You can learn a lot by playing with it.
import inspect
inspect.getcallargs(symlinks, 'releasepath', 'deploypath', 'settingsfile', is_file=True)
=>
{'deploy_to': 'deploypath',
'is_file': True,
'release_path': 'releasepath',
'roll_back': False,
'settings_file': 'settingsfile'}
Python will bind the passed in values to the positional parameter names in the order they are passed, unless you specify a parameter name explicitly.
In your case, if you invoked the function with: symlinks(releasepath,deploypath,True), then the default values would be used for the remaining 2 parameters (roll_back and is_file).
See documentation: https://docs.python.org/2/tutorial/controlflow.html#keyword-arguments
Can you please help me guys. I believe I've got pretty easy questions but don't want to stuff up with my assignment. I'm going to have Class in my module, this class will have few functions.
I just want to be sure it works alright and this is a not ugly code practice.
I.e. my first function test_info accepts one parameter test_code and returns something and the second function check_class accepts two parameter, one of them is called test_code as well
Can I use same argument name: test_code? Is it normal code practice?
def test_info (self, test_code):
my_test_code = test_code
#here we'll be using my_test_code to get info from txt file and return other info
def check_class (self, test_code, other_arg):
my_test_code = test_code
#here some code goes
Also is it fine to use my_test_code in both functions to get argument value or is it better to use different ones like my_test_code_g etc.
Many thanks
Yes you may.
The two variables test_code are defined only in the scope of their respective functions and therefore will not interfere with one another since the other functions lie outside their scope.
Same goes for my_test_code
Read online about variable scopes. Here is a good start
There is no technical reason to resolve this one way or another. But if the variables don't serve exactly the same purpose in both functions, it's confusing for a human reader if they have the same name.
I am trying to create an user interface using argparse module.
One of the argument need to be converted, so I use the type keyword:
add_argument('positional', ..., type=myfunction)
and there is another optional argument:
add_argument('-s', dest='switch', ...)
in addition, I have
parsed_argument=parse_args()
However, in myfunction, I hope I can use an additional parameter to control the behavior, which is the optional argument above, i.e.
def myfunction(positional, switch=parsed_argument.switch):
...
How can I achieve that?
Simple answer: You can’t. The arguments are parsed separately, and there is no real guarantee that some order is maintained. Instead of putting your logic into the argument type, just store it as a string and do your stuff after parsing the command line:
parser.add_argument('positional')
parser.add_argument('-s', '--switch')
args = parser.parse_args()
myfunction(args.positional, switch=args.switch)
I'm not sure I did understand correctly what you want to achieve, but if what you want to do is something that looks like:
myprog.py cmd1 --switcha
myprog.py cmd2 --switchb
yes you can, you need to use subparsers. I wrote a good example of it for a little PoC I wrote to access stackoverflow's API from CLI. The whole logic is a bit long to put thoroughly here, but mainly the idea is:
create your parser using parser = argparse.ArgumentParser(...)
create the subparsers using subparsers = parser.add_subparsers(...)
add the commands with things like `subparser.add_parser('mycommand', help='Its only a command').set_defaults(func=mycmd_fn) where
mycmd_fn takes args as parameters where you have all the switches you issued to the command!
the difference from what you ask, is that you'll need one function per command, and not one function with the positional argument as first argument. But you can leverage that easily by having mycmd_fn being like: mycmd_fn = lambda *args: myfunction('mycmd', *args)
HTH
From the documentation:
type= can take any callable that takes a single string argument and returns the converted value:
Python functions like int and float are good examples of a type function should be like. int takes a string and returns a number. If it can't convert the string it raises a ValueError. Your function could do the same. argparse.ArgumentTypeError is another option. argparse isn't going to pass any optional arguments to it. Look at the code for argparse.FileType to see a more elaborate example of a custom type.
action is another place where you can customize behavior. The documentation has an example of a custom Action. Its arguments include the namespace, the object where the parser is collecting the values it will return to you. This object contains any arguments have already been set. In theory your switch value will be available there - if it occurs first.
There are many SO answers that give custom Actions.
Subparsers are another good way of customizing the handling of arguments.
Often it is better to check for the interaction of arguments after parse_args. In your case 'switch' could occur after the positional and still have effect. And argparse.Error lets you use the argparse error mechanism (e.g. displaying the usage)