简体   繁体   English

python-检查分配并退出(如果无)的pythonic方法

[英]python - pythonic way to check assignment and exit if None

I was looking for a python analogous of (C) 我正在寻找类似(C)的python

 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 ? 诸如user = getUser() or return类的东西不起作用, if (user = getUser() is None) return -pythonic的方式是什么?

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. 如果您正在寻找一种一次性分配和检查分配的值的方法,那么就没有办法了,Python劝阻您不要创建一个。

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 get_user()返回您可以调整的类类型

  • You are willing to define two special functions in the class returned by get_user , namely 您愿意在get_user返回的类中定义两个特殊函数,即

     __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 现在,假设您的User类已经准备就绪,那么您可以编写以下内容

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. 因此,这种分配发生在with语句中,该语句在进入和退出上下文管理范围时调用您的特殊方法。 Inside those methods you can specify the checks and the behavior uppon failure or success to comply with your specifications 在这些方法中,您可以指定检查以及行为失败或成功以符合您的规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM