Python — Passing Multiple Arguments - python

This works in the context of the lesson [Codecademy].
n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(lst):
concat = ""
for string in lst:
concat += string
return concat
However, when I do this in regular Python, outside of the Codecademy environment, and I pass multiple arguments to the function, it returns an error. I was wondering how to make sure that the parameter of the function is a list. This way, I can pass however many arguments I want and the function will simply understand that this is a list.
Note, I do not want to do this with *args or something similar. I was simply wondering if there's a way to pass an actual list into a function.
Would you have to do something like a dictionary?

To pass a list to a function:
join_strings(["Michael", "Lieberman"])

Use asteric operator -
def join_strings(*lst):
Your function will interpret the positional parameters as list

You can pass the list as argument to the function for example in your program you can pass the list like this
n = ["Michael", "Lieberman"]
join_strings(n)
The above code passes list n to join_strings function
To check whether the passed argument is list or not you can have a checking condition like this
def join_strings(lst):
if isinstance(lst, list):
#do something
else:
# do something else
in the above code isinstance() method is used to check whether the passed argument is list or not

I’m sorry guys, apparently I did something wrong when I was typing it into the Terminal or something. Or possibly the way that Sublime (used to) interact with the pre-installed Python stuff on Mavericks. It works fine now, from Sublime and from the Terminal. I’m really not sure what the original problem was or where it was coming from.
— Typing the code in as I had it the first time gave me exactly what I wanted, and then I tweaked it to add a space between the concat strings.
def join_strings(lst):
concat = ""
for string in lst:
concat += (string + " ")
return concat
Thanks for all the help, though. Sorry to bother. :)

Related

Is it possible to store a function and its arguments in a variable?

I have seen lots of information on storing functions in variables for execution, but the functions shown are always of the:
def foo():
print("Hello")
x = foo
x()
variety. Is it possible to store a function and its variables for later execution? I've currently worked around this by creating a tuple with the function as the first item and the variables as a nested tuple for the second item and then calling:
menu_input[KEY_D] = action_system.drop_item, (character,))
...LATER IN CODE...
for key in current_input:
if key in menu.menu_input.keys():
func, args = menu.menu_input[keys]
func(*args)
but I would really prefer to be able to store the function and its variables all together.
I would prefer to be able to store:
menu_input[KEY_D] = action_system.drop_item(character)
...LATER IN CODE...
for key in current_input:
if key in menu.menu_input.keys():
menu.menu_input[keys]()
because the function that handles menu input does not understand or care about the menu function itself, so it really doesn't need to see the input or care about the arguments passed.
Is this possible? If so, what am I missing? Sorry if this is obvious or obviously a bad idea--relatively new to python. If it is a terrible idea, I'd love to know why. I'm avoiding making this a class function of the menu item because I'm trying to work within an entity-component-system model where components store all data and the systems operate on them.
The functools.partial function is made for this purppose:
from functools import partial
menu_input[KEY_D] = partial(action_system.drop_item, character)
...
for key in current_input:
if key in menu.menu_input:
menu.menu_input[key]()
You could choose to use a lambda expression with no arguments.
def foo(value):
print(value)
x = lambda : foo("Hello")
x()

My function for some reason auto-converts a string into a tuple?

I'm very confused here. I'm trying to pass an optional string parameter to my function, but once the parameter is added, it converts the string to a tuple? How can I stop it from doing that or convert back?
I have this:
def fen2grid(note, *optional)
print(optional)
# here it does other stuff
With this when I call it:
fen2grid(example, '.')
now... the print is supposed to print a period. Just .
This is just a test before I use it in the function and it seems to be a good thing that I'm testing it.What it prints is
('.',)
I need the period because I need to work with that (it can be any other symbol too)
Any help would be appreciated!
*args reads an arbitrary number of arguments and encloses them as a tuple. To access them you can simply do print(args[0]) or [print(x) for x in args]
Edit: Keep in mind that neither args or kwargs are keywords, you can replace them for any other placeholder preceded by * or **
I'm trying to pass an optional string parameter to my function
*optional isn't quite how you do that. At least not for default/keyword argument like you are trying to use. That is a tuple.
Try
def fen2grid(note, optional=None)
print(optional)
For more details, see about Defining Functions.

Parentheses in Python's functions and decorators(wrappers)

Thanks for reading my question. As I'm still new to Python, I would like to ask about the () in Python.
def addOne(myFunc):
def addOneInside():
return myFunc() + 1
return addOneInside # <-----here is the question
#addOne
def oldFunc():
return 3
print oldFunc()
Please note that on line four, although the programme returns a function, it does not need parentheses(). Why does it NOT turn out with an error for syntax error? Thank you very much for your answers in advance!
The parentheses are used to run a function, but without them the name still refers to the function just like a variable.
return myFunc() + 1
This will evaluate the myFunc function, add 1 to its value and then return that value. The brackets are needed in order to get the function to run and return a numeric value.
return addOneInside
This is not actually running addOneInside, it is merely returning the function as a variable. You could assign this to another name and store it for later use. You could theoretically do this:
plusOne = addOneInside
plusOne()
And it will actually call the addOneInside function.
The particular instance in your initial question is known as a Decorator, and it's a way for you to perform code on the parameters being passed to your function. Your example is not very practical, but I can modify it to show a simple use case.
Let's say that you want to only have positive numbers passed to your function. If myFunc is passed a negative number, you want it to be changed to 0. You can manage this with a decorator like this.
def addOne(myFunc):
def addOneInside(num):
if num < 0:
num = 0
return myFunc(num)
return addOneInside # <-----here is the question
#addOne
def oldFunc(number):
return number
To explain, the #addOne is the decorator syntax, and it's attaching the addOneInside function to be called on the argument/s of oldFunc whenever you call it. So now here's some sample output:
oldFunc(-12)
>>> 0
oldFunc(12)
>>> 12
So now you could add logic to oldFunc that operates independently of the parameter parsing logic. You could also relatively easily change what parameters are permitted. Maybe there's also a maximum cap to hit, or you want it to log or note that the value shouldn't be negative. You can also apply this decorator to multiple functions and it will perform the same on all of them.
This blogpost explained a lot for me, so if this information is too brief to be clear, try reading the long detailed explanation there.
Your indentation in function addOne() was incorrect (I have fixed it), but I don't think that this was your problem.
If you are using Python3, then print is a function and must be called like this:
print(oldFunc())

Pass one element of tuple as argument along with other arguments

I have a library function that returns a tuple and looks something like this
def some_function(some_string):
does something
return (text,id)
Now I want to pass the text returned from the some_function as argument to another function. The catch is the function has other arguments as well and I don't want to pass the entire tuple as a pointer. I also need need to retrieve many texts that will be generated by different values of some_string.
Depending on the condition met, I want to call another function which will look something like this
if abcd:
other_function(name,phone,**some_function("abcd")**,age)
elif xyz:
other_function(name,phone,**some_function("xyz")**,age)
else:
other_function(name,phone,**some_function("aaaa")**,age)
So what should I replace some_function("abcd") with so that it sends only the text and not both text and id as arguments?
The other_function is defined like this
def other_function(name,phone,text,age):
...
return
One solution that I came up with myself was to create another function that returns just the text.
def returntextonly(some_string):
self.some_string = some_string
(text,id) = some_function(some_string)
return text
and then call the other_function like
if abcd:
other_function(name,phone,returntextonly("abcd"),age)
I mostly program in C++ and have picked up python only recently. I was wondering if there is a better solution to the problem than creating a new function just to return one element of the tuple.
Thanks for reading.
You can run this as:
other_function(name, phone, some_function("abcd")[0], age)
There is no need to define the additional if statements, wrapper functions etc, since you want to pass only the first element of the tuple which is returned from the original function.
For the general case, this becomes:
other_function(name, phone, some_function(some_string)[0], age)
Note that the tuple is another (immutable) iterator, and its elements can be accessed using the regular indexes like in lists.

Passing arguments to functions in Python using inspect

I have a Python script which creates a dictionary of its own functions and I'd like it to execute them by reading in a function name and arguments using YARP (knowledge of YARP is irrelevant to this question though).
I create a list of strings called "inc" which is populated by values coming into the program. The first item is a function name, and any other strings in the list are arguments. I create a dictionary called "methods" where the key is the function name and the value is a reference to the function object (using the inspect module). I store the return value of the function in a variable "result".
The snippet below shows a simplified version of what I'm using so far, which works fine, but can't handle functions with more than one argument. To circumvent this I use a list if a function needs more parameters:
if len(inc) == 1:
result = methods[inc[0]]() # call method with 0 arguments
elif len(inc) == 2:
result = methods[inc[0]](inc[1]) # call method passing a string
else:
args = []
result = methods(inc[0])(inc[1:]) # call method passing a list
Ideally, I'd like to change this so that my functions can have any number of arguments, but I can't figure out how I can do this. I'm new to Python and I have looked at the documentation and various websites - I just can't find a solution. I've tried things like creating a tuple of the arguments, but that doesn't work either as it ends up passing the whole tuple in as one parameter.
Is there a better solution to this problem, like creating some kind of object which represents a set of parameters and passing that into the function? Any suggestions would be greatly appreciated!
You should check out https://stackoverflow.com/a/3394898/1395668.
The magic you are looking for is the *. Apply this to your list and it unpacks the items into the argument fields of your function:
a = [ 1, 2, 3]
def myfunc(a, b, c):
return a + b + c
print myfunc(*a)
Check out ** for the same approach for dict
It's a bit strange to have this kind of mixed structure:
inc = [func_name, arg1, arg2, ...]
Wouldn't it be much more natural to have two separate bits of information?
func_name = ...
args = [arg1, arg2, ...]
The you could do
methods[func_name](*args)
(Usually, I wouldn't bind the functions name to a variable, but preferably the function itself.)

Categories