I was looking for a python analogous of (C)
if ((p = malloc(N * sizeof(*p))) == NULL) return 1;
Something like user = getUser() or return
does not work nor would if (user = getUser() is None) return
- what's the pythonic way ?
If you are looking for a way to assign and check the assigned value in one go, there isn't one, and Python dissuades you from creating one.
user = get_user()
if user is None:
return None
You could use context management under two conditions:
The get_user()
return a class type you can tweak
You are willing to define two special functions in the class returned by get_user
, namely
__enter__(self) __exit__(self, exception_type, exception_value, traceback)
Now, lets suppose your User
class is all set and ready, then you could write the following
with get_user() as user:
# do what you need to do
So this way the assignment happened in the with
statement which calls your special methods upon entering and exiting the context management scope. Inside those methods you can specify the checks and the behavior uppon failure or success to comply with your specifications
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.