Beginner Here and I just want to know how to skip a parameter in python for example
def function(a, b):
pass
function(5)
I want to only assign 5 to b. How can I do it?
You can do this:
def function(a=None, b=None):
pass
function(b=5)
This makes the values that don't get assigned None (in this case a is gonna be None).
If you don't add =None to the two parameters, it will throw an error because I didn't assign anything to a.
If in the last line you don't say b=5 and instead say just 5, it will think that is for the a parameter since the a parameter is before the b parameter in the parenthesis.
Simply, You can set a default value to a in that case.
def function(b,a=None):
pass
function(5)
Please note that the default parameters are supposed to follow the non-defualt ones.
Related
I am wondering how a function is processed in a certain language due to the two errors caused by the following two functions in Python.
def fun(a=[0], b: int):
pass
The error reads that SyntaxError: non-default argument follows default argument.
# to show that this function is not trivial
def fun(a:list=[0], b=len(a)):
pass
Araises the error: NameError: name 'a' is not defined
The first example shows obviously that a is processed before b, that is the compiler should know a when it encounters b, but it seems that the compiler doesn't as shown in the second example.
When(or how) is a parameter defined in a function? Or how can I know what's going on under the hood? I mean the related part of the compiler code, may be implemented in context-free grammar.
The parameter a is a local variable that doesn't actually get defined until the function is run; it's not available as a default argument value for b. Such a value needs to exist when the function is defined.
The first example shows obviously that a is processed before b
Not really, at least not in the full meaning of "processed".
The "compiler"/"pre-processor" (non of these terms really apply to Python, but let's let them) can easily check if you use = with an argument before another argument which does not have it by just building the AST tree, without "executing" the actual code.
So, fun(a=0, b) is wrong on the language syntax level (hence the SyntaxError). It is detected before the code is even executed, and its presence stops the parsing and the "compilation" of the code.
fun(a=0, b=a) is logically wrong. The syntax checking mechanism can't/won't detect it. It is only detected by the interpreter when it is trying to execute the code.
def fun(a=0, b):
Here you have a default value for a, but none for b. That means you must provide a value for b when calling the function, but not for a. However, when you call it like so:
fun(42)
Which argument will receive the value? b, since a already has one?
That syntax just raises all sorts of questions, hence you must list all parameters with a default value last. That is the reason for that error.
def fun(a=0, b=a):
Here you're trying to assign the value of a variable a as the default value for b. That is fine in general:
bar = 'baz'
def fun(foo=bar): ...
The default value is evaluated once at function declaration time. The a in b=a does in no way refer to the a in a=0 from the same function declaration. It's looking for a variable a in scope, which it doesn't find.
Arguments are processed in the order they appear, but if you are going to set a default parameter for any argument then they need to come at the end. Proper syntax would be def (b, a=0). In this case b is a required argument, and a is optional which defaults to 0 if nothing is passed.
I came across a python code in Django in which '=' was used in an unusual way. Can anybody please explain what it means. This is the line of code:
return reverse('model-detail-view', args=[str(self.id)])
Here reverse is a function and it's value is being returned. The first argument is understandable but the second argument uses a '=' symbol. How is this working? What does it do?
The call to reverse is passing a list to the argument called args of the function.
In python you can omit arguments with default values. for example if your function like this:
def func(a, b=None, c=None):
....
you must pass a but you can omit b and c. if you want to pass only c and you can pass it with name like this:
func(a, c=c_val)
by this call python use default value for b and run code.
the reverse function get 5 argument. one argument is required and 4 is optional. this code pass third argument and left other as default. the third argument is a list.
Suppose I have an old function, oldFunction(first, second, third). And, all the arguments are mandatory. I want to deprecate the use of 'second' argument, and also not change the code anywhere in my project.
I want to create a new function which does exactly the same thing, with only the first and the third argument.
I was thinking of wrapping the new function with new signature with old function as the wrapper. How can I possibly do that? Hence I will be able to use the new function with only two arguments, but when called by the old name, will the new function be called (because it is wrapped)?
How can I do that?
Once you have newFunction(x,y) defined you can redefine oldFunction as:
def oldFunction(x,y,z):
return newFunction(x,z)
Why not use keyword arguments? This way you could have both:
def function(a, b, c=None):
pass
And you can call it function(a, b) and also function(a, b, c).
While I'm going through Python code and seeing functions called, I notice things like
functionCall(argument='something')
or
someclass.functionCall(argument='something')
I've played around with it and noticed you have to name that variable with the same name as the one in the scope of the function or class function itself. Is that just a convention (for useful naming) or is there more to it that I'm missing?
Those are just standard keyword arguments.
They are mainly useful when calling functions that usually assume default values, but the user is interested in passing a custom value without affecting the other defaults.
For example:
def foo(a='a', b='b', c='c'):
print a + b + c
Then:
>>> foo()
'abc'
>>> foo(c='x') # don't know or care about a and b's value
'abx'
This is called a keyword argument. Keyword arguments have a couple distinct advantages:
They can be specified in any order by the caller.
They have default values, which means the caller doesn't have to provide a value for each argument if the defaults are sensible.
They can make code more readable. For example, foo(width=100, height=200) is easier to understand than foo(100, 200). It is also easier to use, because you don't have to remember whether the function takes width,height or height,width.
It is good to have named arguments as arguments can be specified in any order by using named arguments.
Even required arguments (like object, which has no default value) can be named, and named arguments can appear in any order.
Also see This
Python's argument passing mechanisms are extremely flexible.
cons: too many arguments to a function. Solutions: split into multiple functions, pass some args together in a dictionary or object.
cons: bad variable names. Solution: give variables more descriptive names.
Or remember the correct order .. :)
class xyz:
def __init__ (self, a='1', b='2'):
print a,b
xyz(b=3,a=4)
xyz(a=5,b=6)
>>4 3
>>5 6
these are keyword parameters. They enable you to pass parameters in any order (useful for skipping optional parameters)
Please note though, calling functions that way comes with a little bit of overhead:
def test(a,b,c):
return a+b+c
def t1():
return test(1,2,3)
def t2():
return test(a=1, b=2, c=3)
timeit(t1)
0.23918700218200684
timeit(t2)
0.2716050148010254
I have a function which returns 3 numbers, e.g.:
def numbers():
return 1,2,3
usually I call this function to receive all three returned numbers e.g.:
a, b, c = numbers()
However, I have one case in which I only need the first returned number.
I tried using:
a, None, None = numbers()
But I receive "SyntaxError: assignment to None".
I know, of course, that I can use the first option I mentioned and then simply not use the "b" and "c" variables. However, this seems like a "waste" of two vars and feels like wrong programming.
a, _, _ = numbers()
is a pythonic way to do this. In Python 3, you could also use:
a, *_ = numbers()
To clarify _ is a normal variable name in Python, except it is conventionally used to refer to non-important variables.
Another way is of course a=numbers()[0], if you do not want to declare another variable. Having said this though, I generally use _ myself.
The way I do it:
a = numbers()[0]
Seeing as the type returned is a tuple, you can access it via index.
This solution keeps you from having to declare unused/meaningless variables such as "_". Most people don't mind unused variables, however my pylint is setup to warn me of such things as they could indicate potentially unused code, etc.