I came across something I don't quite understand with how the parameters in the def function works:
ie:
def test(a=1, b=9, c='what'):
return a
test(a,b,c)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-295-937fe43dbbd5> in <module>()
2 return a
3
----> 4 test(a,b,c)
NameError: name 'a' is not defined
and
def test(a=1, b=9, c='what'):
return a
test('what')
Output: 'what'
Well, I am looking to set the parameters a,b as default values. Now, for the 1st example, if I call test(a,b,c), it says a is not defined. However, I have already "defined" it in the function parameter? That means, if let's say a, b and c are default parameters, I cannot execute test(a,b,c)? Only test() works? WHAT!
In example 2, I don't even know anymore...
The problem is that you are trying to call your method test with three variables which do not exist in the global scope where you are running the method.
The way you are defining your method:
def test(a=1, b=1, c=1)
does not imply that the arguments a, b, c are available to be used globally the way you are trying to use them.
By defining your method as a=1, b=1, c=1, you are setting default values to your arguments. What this means, is that you can call your method with or without passing arguments to your method.
So, for your first example, you can call it like this:
test(a="what")
Which indicates that now you are assigning "what" to a and will no longer hold its default value of "1".
Alternatively, you can simply call it without any arguments, which in turn would assign default values to your local arguments inside your method. So, if you actually call your method like this:
test()
Then, the default value of "1" will now be assigned to "a".
In your second example, you are passing a string, and by default, your parameters get assigned from left to right of your function definition. So, when you do this:
test("what")
You are assigning "what" to a.
Related
So I use a bunch of files. Each file will trigger when lets say variable x = function. I know this is confusing but pretty much I need to be able to use a variable name which depending on what the variable is equal to will call that function. I am using python for this.
Based on your question, it looks like you want some sort of factory where the function to call is determined by the value of the variable passed in.
Here's a simple way of doing it:
x = 2 # determines which function to call
# possible functions to call
def f0(p): print('called f0',p)
def f1(p): print('called f1',p)
def f2(p): print('called f2',p)
def f3(p): print('called f3',p)
lstFunc = [f0, f1 ,f2, f3] # create list of functions
lstFunc[x]('test') # x=2, call function at index 2 (f2)
Output
called f2 test
For something more complicated, you would use a function which returns another function based on the variable value. In this example, I'm just using a list of functions.
So this is the default behavior when you give a bad variable name:
>>> foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>>
what I'm looking for is something like:
>>> set_name_error_handling('assign_default',None)
>>> foo
>>>
(foo is automatically assigned None)
I'm using this on dynamic parameter handling and would like to use a behavior that if the parameter is not given, a default value is being used. And I have some code that I don't have control of that have used None handling. Is it possible for me to just add some dynamic header like below and save the mess by not changing all other code?
# This may work in python2 but not python3
def foo(self,params):
local = locals()
for key in params:
local[key] = params[key]
# Do important things onwards, cannot change
Edit: A way to do the specific problem above, is to provide a default option, let's say:
options = foo.get_default_params()
# do whatsoever changes to modify options
result = foo.call(options)
This assumes that a default parameter table is available. Is it still doable when you don't even have the default parameter table or it's not possible to generate one (infinite possible parameters like print())?
Edit: To center the question into methodology I have rephrased the title and removed reference to override NameError.
I don't think Python offers something like that. However, you could always do:
try:
foo
except NameError:
foo = None
# do whatever with foo
If you are trying to define a function, I would define it like this:
def baz_func(foo=None):
# function body here
You can call this as both baz_func() or baz_func(foo=5).
I'm new to programming and I've been stuck on this issue and would really like some help!
One of the parameters in my function is optional, but can take on multiple default values based on another function. Both functions take in the same input (among others). When I try to assign a default using the function as illustrated below:
def func(foo):
# returns different values of some variable k based on foo
def anotherFunc(foo, bar, k=func(foo)):
# this is the same foo input as the previous function
I get the following error:
NameError: name 'foo' is not defined
The thing is, the user can call 'anotherFunc' with any value of 'k' they want, which complicates things. Is there any way to have a function with arguments in it as a parameter in another function? Or is there any way for me to set multiple default values of 'k' based on the previous function while still allowing the user to choose their own 'k' if they wanted?
Thanks!
foo at the moment of defining the function acts as placeholder for the first function argument. It has no value until the function is called, for which its value can be accessed in the function body, like so:
def another_func(foo, bar, k=None):
if k is None:
k = func(foo)
...
You would probably want to do something like:
def func(foo):
return foo
def anotherfunc(foo, bar, k=None):
if k == None:
k = func(foo)
#process whatever
Suppose there is a function defined as
def function1(x, y, z=True,a):
...
...
When I call function1, it seems I can call the function in the following manners
function1(10,2,3)
function1(x=10,y=2,a=3)
But calling function1(x=10,y=2, 3) will cause error, where 3 should be assigned to a. Generally, what are the correct ways to call a function withou causing potential issues.
That is not a valid way to define a function in python 2 or 3. Default arguments (ones with default values, namely x=y) must come after non-default arguments. With your function definition, you should receive the following error:
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 8 years ago.
I have a python programming question, I am using a caching pattern to speed up computation, here is an example code:
def f(a=1, a_dict={}):
try:
b=a_dict['one']
print 'fetched from cache'
except:
b=10
a_dict['one']=10
print 'put in cache'
return b
Now if I call this function the first time the result is:
>>> f(1)
put in cache
10
I call again:
>>> f(1)
fetched from cache
10
This is nice a behaviour since it uses caching. However, I find it strange because the variable a_dict has been defined within the function, so once the function is over it should be out of scope... Note that this variable is not visible from outside the function:
>>> a_dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a_dict' is not defined
I would have guessed that when I call the function the second time, the default variable a_dict should have been initialized to {}, so I find it strange that when I call f() the second time the previous value of a_dict is somehow still in scope.
In summary, I would have expected to achieve the desired behaviour like this:
the_dict={}
f(1, the_dict)
# call second time
f(1, the_dict)
Because the object the_dict is passed by reference and hence stays in scope.
Can someone please explain the semantics of parameter initialization in a function and their scope?
Functions are objects in python, so default parameters can be thought of as 'members'. It is explained fully: http://effbot.org/zone/default-values.htm
To get the behaviour you expect, you can have the function defined as follows:
def f(a=1, a_dict=None):
if a_dict is None:
a_dict = {}
try:
b=a_dict['one']
print 'fetched from cache'
except:
b=10
a_dict['one']=10
print 'put in cache'
return b
This means that, rather than the {} being made when the function is defined (and therefore retained in it's object def), it's made when the function is run (and therefore is a local variable).