Given the following two methods:
def test():
string = "{test}"
print convert(string, test='test')
def convert(string, **test):
return string.format(test)
Why does this throw an KeyError: 'test'?
As I have seen in other threads, this should be a valid way of passing values, shouldn't it?
As shown in the question you linked to, you need to expand the keyword-argument dictionary when passing it to format:
return string.format(**test)
Related
I'm having difficulty understanding how to use return values.
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
print(grab("users/self/profile", "janice"))
I need to consume the result of passing the first function in order to print the user info. But I'm not sure how to do that...the second function is not supposed to consume a string or call the function directly. I understand the return value doesn't exist outside the scope of the first function so I don't understand how to get the value into the second function without just calling it directly as I have above.
The first function is basically returning a dictionary and the second function needs to consume the result of calling the first function.
I think this small modification is what you are seeking.
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
print(grab_name("janice"))
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
return "janice"
print(print_user_info(grab_name))
result :
janice
Let's say I have a function that can take various kinds of parameter values, but I don't want to (as a constraint) pass arguments explicitly. Instead, I want to pass them as a string.:
def func(param)
return param+param
a = 'param=4'
func(<do something to a>(a))
>>8
Is this possible in python?
I want to use this idea in Django to create Query filters based on GET parameters in a dictionary and then just chain them using their keys.
lookup_dic = {'user': 'author=user',
'draft': 'Q(publish_date_lte=timezone.now())|
Q(publish_date_isnull=True)'}
Based on whether the user and draft keywords are passed in the GET parameters, this would be read out like:
queryset.objects.filter(author=user).filter(Q(publish_date_lte=timezone.now())|
Q(publish_date_isnull=True))
I understand that I can do this by replacing the author=user by Q(author__name=user), but I wanted to know if this string comprehension feature is implemented in python in general?
Use eval
def func(param=0):
return param+param
a = 'param=4'
eval('func(' + a +')')
Are you looking for this?
def func(param):
return param + param
a = 'param=4'
parameter, value = a.split("=")
print(func(**{parameter: int(value)}))
# >> 8
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.
Let's say I have the following two variables:
import datetime as dt
a = None
b = dt.datetime(2017, 11, 30)
def str_format(str):
return '{:%Y-%m-%d}'.format(str)
The following would return a formatted string:
str_format(b)
'2017-11-30'
But the following would return an error:
str_format(a)
TypeError: unsupported format string passed to NoneType.__format__
So far I can up with the following solution:
def str_format(str):
if isinstance(str, type(None)) is False:
return '{:%Y-%m-%d}'.format(str)
else:
return '{}'.format(str)
str_format(a)
'None'
str_format(b)
'2017-11-30'
However, I was looking at a more efficient/cleaner way of writing the function.
Often times these types of things are wrapped in a try/except
def str_format(str):
try:
return '{:%Y-%m-%d}'.format(str)
except TypeError:
# unrecognized type, return blank or whatever you want to return
return ''
The answer on this question explains why you typically use try/except instead of a conditional check fairly well.
your function is overcomplex. None is a singleton, so the pythonic way of testing against it is just is None.
Just do it in one line with a ternary expression:
def str_format(s):
return str(s) if s is None else '{:%Y-%m-%d}'.format(s)
or to return a default date (ex: 1/1/2010) if None is passed:
def str_format(s):
return '{:%Y-%m-%d}'.format(s or dt.datetime(2010, 1, 1))
as a side note don't use str as a variable name as it is the python string type.
i am just trying...but the self.value show error ie...i want to loop self.a,self.b,self.c...help require for learning help required......output wanted is x= [AA,EE,II] using classes and loops.i tried looping the self.a,self.b,self.c using for loop.........i am learning python and object oriented programming newly....help me out
import string
A = ["AA","BB","CC","DD"]
B = ["EE","FF","GG","HH"]
C = ["II","JJ","KK","LL"]
class User:
def __init__(self,A,B,C):
self.a= A
self.b= B
self.c= C
def User1(self):
x=[]
for i in range(ord('a'), ord('c')+1):
value= chr(i)
x.append= self.(value)[0] ///for getting first elemen from A,B,C
i+=1
return x
honey= User(A,B,C)
print(honey.User1())
WHat you want is to use getattr - but there are a few other things broken there. (to start with the fact that the comment character is # in Python, and not the // sequence.
So, your User1 method could be something like:
def User1(self):
x=[]
for value in "abc":
x.append(getattr(self, value)[0])
return x
Note as well that the for statement will always iterate over a sequence, and you don't need to go long ways to convert your sequence to numbers, just for converting those numbers back to the desired elements. As a string is also a sequence of characters - just looping over "abc" will yield your desired letters.
As stated above, the getattr built-in will then retrieve the desired attribute from self gven the attribute name as a string, contained in the value variable.
I have a python function that returns
def edit_user(request):
error = False
errMsg = ""
id = int(request.POST.get("add_user"))
if config.editUser(id) != True
error = True
errMsg = _('Failed to edit existing user.')
return [error, errMsg]
I'm calling this function from another python function.
How do I get these two return values, (error and errMsg) into two separate variables?
Like this: error, errMsg = edit_user(request).
Just assign the results to a list or tuple:
error,errMsg = edit_user(...)
(error,errMsg) = edit_user(...)
[error,errMsg] = edit_user(...)
The first syntax is the most preferable.
Hui Zheng is right - error, errMsg = edit_user(request) will do it.
The process is called unpacking and can be used to unpack complicated data structures (see this SO question for another example, and have a look at the python docs for more info).
Just to add to other answers: there's no reason to make a list here at all. Just do this:
return error, errMsg