Let's say we have
def Foo(Bar=0,Song=0):
print(Bar)
print(Song)
And I want to assign any one of the two parameters in the function with the variable sing and SongVal:
Sing = Song
SongVal = 2
So that it can be run like:
Foo(Sing=SongVal)
Where Sing would assign the Song parameter to the SongVal which is 2.
The result should be printed like so:
0
2
So should I rewrite my function or is it possible to do it the way I want to? (With the code above you get an error saying Foo has no parameter Sing. Which I understand why, any way to overcome this without rewriting the function too much?
Thanks in advance!
What you're looking for is the **kwargs way of passing arbitrary keyword arguments:
kwargs = {Sing: SongVal}
foo(**kwargs)
See section 4.7 of the tutorial at www.python.org for more examples.
Related
so I want to know if there is a solution to make an argument which is not organised when I create an object.
class Joueur:
nbrJoueur=0
def __init__(self,c_pseudo,c_pv=25,c_sttat=0):
self.pseudo=c_pseudo
self.pv=c_pv
self.sttat=c_sttat
Joueur.nbrJoueur+=1
j1=Joueur("adel",250,0)
j2=Joueur("salah",c_sttat=10)
So like in j2 I had to make c_sttat=10 to avoid that it's the the c_pv which take the value 10.
So I want to avoid that problem when I have a lot of arguments how could I do that?
I think this may be what you want:
def __init__(self,c_pseudo, *, c_pv=25,c_sttat=0):
When you put * in the parameter list, all the arguments after that position must be given with keywords. So if you try to write
j2 = Joueur("joseph", 10)
you'll get an error because you didn't name the second argument. This forces you to indicate whether it's c_pv or c_sttat
I have a function which takes 1 argument. The function outputs several results and assigns them to a variable for later use. I would like to change the variable names using the argument but I am unsure how to do so. What I envison is something like what I have written below, but this returns a syntax error and I am not sure where to go from here.
Thank you!
def Get_Sums_Counts(Category):
{Category}_Total_Count = len(Analyzed_Month[Analyzed_Month['age_cat'] == Category])
return {Category}_Total_Count
{Category}_Total_Sum = round(Analyzed_Month[Analyzed_Month['age_cat'] == Category].sum())
return {Category}_Total_Sum
I've created a function which can take a parameter which defines another call to manipulate a list. For example if I call sliprotor(Rotorid1, 1) directly, then the Rotorid1 list is manipulated as I want. Function below:
def sliprotor(rotorid,offset_qty):
for movers in range(26,0,-1):
rotorid[movers-1+offset_qty]=rotorid[movers-1]
for movers_refill in range(offset_qty):
rotorid[movers_refill]=rotorid[movers_refill+26]
However, if I try to call this 'indirectly' by building the list name and then executing it, 'rotorid' is not translated to the value, as it is when called directly.
The way I am doing this is
def set_curr_rotor(XX):
rotorid = "Rotorid"+str(XX)
return rotorid
rid1 = input("First rotor slip : ")
if(rid1):
sliprotor(set_curr_rotor(rid1),1)
So the 'indirect' call doesn't pass the value created by the set_curr_rotor function into the sliprotor function. The direct call does use the passed in value.
If I look in debug, you can see that it is directly calling rotorid[] as the list, not Rotorid1 or other Rotoridx and hence I get an index error.
....
File "", line 3, in sliprotor
rotorid[movers-1+offset_qty]=rotorid[movers-1]
IndexError: string index out of range
I could restructure the way I have the code, but I would prefer not to. Is there some method / scope issue I am missing? Is this just an intrinsic attribute of Python? I'm very new to Python so I'm just doing an exercise to model an Enigma machine.
Any help appreciated.
Ed
I'll assume that you have defined your rotors already, something like this:
Rotorid1 = list('abcdefghijklmnopqrstuvwxyz')
Rotorid2 = list('abcdefghijklmnopqrstuvwxyz')
And now you're reluctant to change this, because ... reasons.
That's fine. But you're still wrong. What you need to do is to create a larger data structure. You can do it like this:
Rotors = [ Rotorid1, Rotorid2, ... ]
Now you have a list-of-lists. The Rotors variable now contains all the various Rotorid variables. (Well, it references them. But that'll do.)
Instead of passing in the variable name as a handle to the rotor, you can simply pass in an index number:
def set_rotor(id):
global Current_rotor
Current_rotor = id
def slip_rotor(amount):
global Current_rotor
global Rotors
rotor = Rotors[Current_rotor]
for movers in range(26,0,-1):
rotor[movers-1+offset_qty]=rotor[movers-1]
# etc...
Also, be sure an look up slicings in Python - you can do a lot by manipulating sublists and substrings using slices.
I'm trying to write a function that will contain some default values, with the possibility of having some additional parameters sent in. For example, I would like something along the lines of this:
def defaultsAndArbitrary(arr, example1=True, example2=13, *modifiers):
#code
Then, I'd like to be able to call the function like so:
defaultsAndArbitrary([1,5,3,9], modifier1, modifier2)
With that call, the values for the arguments should be:
arr = [1,5,3,9]
example1 = True
example2 = 13
modifiers = (modifier1, modifier2)
There's a similar question here:
Having arbitrary number of arguments with a named default in python
But it doesn't really answer this question (at least, to my understanding). Is it even possible to do this?
Thanks.
You can do something like this:
def defaultsAndArbitrary(arr, *modifiers, **kwargs):
example1 = kwargs.get('example1',True)
example2 = kwargs.get('example2',13)
In Python 3 you can use keyword-only arguments. That would look something like this:
def defaultsAndArbitrary(arr, *modifiers, example1=True, example2=13):
In Python 2 you must a use a solution like that given in the question you linked to: you must use **kwargs and manually extract example1 and example2 from the kwargs dict, supplying defaults if those kwargs are not passed. This means that you can't specify their names or defaults in the function signature; you have to do it in the code of the function.
Note that in either case, your example1 and example2 variables must be passed by keyword (if you want to pass values for them instead of using the defaults); they cannot be passed positionally.
Hi I was wondering how to implement this in python. Lets say for example you have a function with two parameters and both print out to console
def myFunc(varA, varB):
print 'varA=', varA
print 'varB=', varB
I have seen libraries (pymel being the one that comes to mind) where it allows you to specify the parameter you are parsing data too by name in no specific order. for example
myFunc(varB=12, varA = 'Tom')
I am not sure what I am missing as this doesn't seem to work when I try to declare my own functions inside or outside the maya environment.
Any clues would be wonderful, thank you in advanced.
That's normal Python behavior. If you're seeing errors then you're goofing up something else (e.g. missing a required parameter, trying to pass positional arguments by name, etc.).
>>> def func(foo, bar):
... print foo, bar
...
>>> func(bar='quux', foo=42)
42 quux