- Converting a string to an argument: A guide
- Python — convert string to argument (or dynamically choose increment duration type for date)?
- How to convert string into argument?
- How do I convert a string into a vector of command line arguments?
- How to convert all arguments to string in string formatting
- Convert String to function call in Python
- String To Function Using The eval() Function In Python
- String To Function Using The getattr() Function In Python
- String To Function Using The getattr() Function And Module Name
Converting a string to an argument: A guide
To read an argument name as a string, inspect.signature(function name).parameters.keys() can be used where the function name is the name of the function whose argument needs to be read as a string. For instance, instead of using the default argument of x, use y and then verify its type within the body of the function. Additionally, using %s may not be able to handle a tuple with 2 elements. It is recommended to use a different approach, such as using a different variable instead of %s.
Python — convert string to argument (or dynamically choose increment duration type for date)?
One can utilize the Python feature of keyword arguments.
some_date = today + relativedelta(**)
It is possible to get the dictionary ready in advance of its usage.
kwargs = <> kwargs['years'] = 10 some_date = today + relativedelta(**kwargs)
- Refer to the Python 2 documentation’s glossary section for the definition of the term «argument».
- The link provided leads to the section of the Python 2 documentation that covers expressions related to function calls.
Eval — python convert a string to arguments list, You want a dictionary, not an ‘argument list’.You also would be better off using ast.literal_eval() to evaluate just Python literals:. from ast import literal_eval params = «<'a': 2, 'b': 3>» func(**literal_eval(params)) Before you go this route, make sure you’ve explored other options for marshalling options first, … Code sample>>> x=’a=2, b=3’>>> args = dict(e.split(‘=’) for e in x.split(‘, ‘))>>> f(**args)a 2b 3Feedback'a':>
How to convert string into argument?
Based on my understanding of your query, you seem to be in search of the symbol denoted as the ** operator.
kwargs = def add(first, second): return first + second print(add(**kwargs) == 9)
Upon applying ** to an argument of type dict , the keyword arguments will be decomposed and printed as True .
To obtain the argument name of a specific function as a string, you can utilize the inspect.signature() function with the function name as its argument. This will return a list of parameter keys for the desired function.
import inspect, itertools dictionary= def func(id,ip): func_argument = list(inspect.signature(func).parameters.keys() ) print(func_argument) #Print the value from dic for each argument which is key in dict for i in func_argument: print(dictionary[i]) func(id=100,ip=200)
Python — convert string to argument (or dynamically, Is it possible to convert string to method’s argument? Let say I can get such strings ‘weeks’, ‘months’, ‘years’. Now I have this: from dateutil.relativedelta import relativedelta from datetime import date today = date.today() So after this I need to increment today by the type of duration that is
How do I convert a string into a vector of command line arguments?
>>> import shlex >>> shlex.split('''-f text.txt -o -q "Multi word argument" arg2 "etc."''') ['-f', 'text.txt', '-o', '-q', 'Multi word argument', 'arg2', 'etc.']
Avoid using Python mutable defaults as default arguments for main . Instead, use argv=None as the default argument and check its type within the body of main . Mutable defaults are considered to be the root of all evil.
def main(argv=None): if argv is None: argv = sys.argv[1:] # .
Python — how to convert string into argument?, python convert a string to arguments list. 1. translate string into function argument.
How to convert all arguments to string in string formatting
Your issue pertains to the incapability of %s to process a tuple comprising of two elements, as demonstrated in the following instance:
>>> "=%s" % ('Goog',) '=Goog' >>> "=%s" % ('Goog','MSFT') Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting
In this case you can make:
import urllib2, json def get_stock_quote(ticker_symbol): if isinstance(ticker_symbol, (list, tuple)): ticker_symbol = ','.join(ticker_symbol) url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol lines = urllib2.urlopen(url).read().splitlines() #print lines return json.loads('[%s]' % ''.join([x for x in lines if x not in ('// [', ']')])) if __name__ == '__main__': symbols = ('Goog',) symbols2 = ('Goog','MSFT') quotes = get_stock_quote(symbols2) for quote in quotes: print 'ticker: %s' % quote['t'], 'current price: %s' % quote['l_cur'], 'last trade: %s' % quote['ltt'] print quote['t'], quote['l'], quote['ltt']
The reason for this error is that the formatting requires a single string, but you provided a tuple with two strings. To obtain http://finance.google.com/finance/info?q=Goog,MSFT, you should follow these steps.
quote = get_stock_quote(",".join(['Goog','MSFT']))
for symbol in ('Goog', 'MSFT'): quote = get_stock_quote(symbol)
Python — change string into arguments and pass it to a, I would like to also add a possibility to store variables in the table, retrieve them on the fly and pass them into the function. However when stored in the db, the arguments are strings, and I don’t know how to convert them to variable names to pass to the function. For instance lets consider the following …
Convert String to function call in Python
Strings are one of the most used data structures when we process text data. We also use different functions in our program. But, have you ever tried to convert a string to a function given that a function with the same name has been defined in a different module or class? In this article, we will discuss how we can convert string to function call using different ways in python
String To Function Using The eval() Function In Python
The eval() function takes a string expression as input, parses it, and returns the output after evaluating the input expression. For instance, we can evaluate a mathematical expression using the eval() function as follows.
We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ‘ () ’ separated by the addition symbol ‘ + ’. Upon execution, the eval() function will call the input function and will return the output of the function whose name was given as the input argument.
For instance, look at the following example.
Here, we have declared a function named ‘ printTenNumbers ’ that prints the numbers from 1 to 10. We have passed the function name i.e. ‘ printTenNumbers ’ and ‘ () ’ separated by + sign to the eval() function. The eval() function first calculated the expression ‘‘ printTenNumbers + “() ”’ to ‘ printTenNumbers() ’. After that printTenNumbers() is executed and the numbers are printed. Hence, we have converted a string to a function in python, Given that a function with the name of the given string is already defined.
String To Function Using The getattr() Function In Python
In python, the getattr() function is used to extract the value of an attribute from a class or a module using its name. The syntax for the getattr() function is as follows.
- The ‘ object ’ may be a class name, a module name, or an instance of a class.
- ‘ attribute ’ is the name of the field , function , or method that we want to extract from the class or the module.
- ‘ default ’ is the default value if the input ‘ attribute ’ name is not found in the object.
Let us understand the working of the getattr() function using the following example.
Here, we have defined a class Laptop with three attributes namely model , RAM , and processor . Then we have created a Laptop object named myLaptop . After that, we have extracted the value of the attribute processor using the getattr() function. We can obtain the value of any attribute of the myLaptop object.
Hence, getattr() function can be used to obtain values of different attributes of a class, object, or module.
Having understood the working of the getattr() function, let us now use the getattr() function to convert a string to function in python.
String To Function Using The getattr() Function And Module Name
If we have the name of a function defined in a different module, we can convert the string to function using the getattr() function. For this, we will pass the name of the function to the getattr() function as the first argument and the name of the module as the second argument. The getattr() function will return a function that will behave exactly the same as the function whose name is given as input.
For instance, we can use the factorial() function defined in the math module using the string ‘ factorial ’ and the module name ‘ math ’ to define a function that behaves exactly like the factorial() function as follows.