Python:一行中的try语句 [英] Python: try statement in a single line

查看:179
本文介绍了Python:一行中的try语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有些东西像...一样吗?

  b ='some variable'
a = c | b #try语句在这里

其中 b 是一个声明的变量, c 不是...所以 c 会抛出错误,一个将成为 b ...

解决方案

p>没有办法在Python中将 try / 除了块压缩到一行。



此外,不知道Python中是否存在变量,这是一件坏事,就像在其他一些动态语言中一样。更安全的方式(和普遍的风格)是将所有变量设置为某事。如果他们可能不设置,请将它们设置为首先(或 0 或更适用的东西。)






如果您 strong>首先分配您感兴趣的所有名称,您有选项。




  • 最佳选项是if语句。

      c =无
    b = [1,2]

    如果c为无:
    a = b
    其他:
    a = c


  • 单行选项是条件表达式。

      c =无
    b = [1,2]
    a = c如果c不是其他b


  • 有些人滥用来做到这一点。

      c =无
    b = [1,2]
    a = c或b

    考虑以下情况:

      c = [] 
    b = [1,2]
    a = c或b

    在这种情况下, a 可能 [] ,但它是 [1,2] 因为 [] 在布尔上下文中为false。因为有很多值可能是错误的,我不使用技巧。 (如果foo不是没有,则他们说如果foo:,那么这个问题与 。)



Is there a way in python to turn a try/except into a single line?

something like...

b = 'some variable'
a = c | b #try statement goes here

Where b is a declared variable and c is not... so c would throw an error and a would become b...

解决方案

There is no way to compress a try/except block onto a single line in Python.

Also, it is a bad thing not to know whether a variable exists in Python, like you would in some other dynamic languages. The safer way (and the prevailing style) is to set all variables to something. If they might not get set, set them to None first (or 0 or '' or something if it is more applicable.)


If you do assign all the names you are interested in first, you do have options.

  • The best option is an if statement.

    c = None
    b = [1, 2]
    
    if c is None:
        a = b
    else:
        a = c
    

  • The one-liner option is a conditional expression.

    c = None
    b = [1, 2]
    a = c if c is not None else b
    

  • Some people abuse the short-circuiting behavior of or to do this. This is error prone, so I never use it.

    c = None
    b = [1, 2]
    a = c or b
    

    Consider the following case:

    c = []
    b = [1, 2]
    a = c or b
    

    In this case, a probably should be [], but it is [1, 2] because [] is false in a boolean context. Because there are lots of values that can be false, I don't use the or trick. (This is the same problem people run into when they say if foo: when they mean if foo is not None:.)

这篇关于Python:一行中的try语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆