简体   繁体   English

Python等同于PHP的@

[英]Python equivalent of PHP's @

Is there a Python equivalent of PHP's @ ? 是否有Python等同于PHP的@

@function_which_is_doomed_to_fail();

I've always used this block: 我一直使用此块:

try:
  foo()
except:
  pass

But I know there has to be a better way. 但我知道必须有更好的方法。

Does anyone know how I can Pythonicify that code? 有谁知道我怎么能Python化该代码?


I think adding some context to that code would be appropriate: 我认为向该代码添加一些上下文将是适当的:

for line in blkid:
  line = line.strip()
  partition = Partition()

  try:
    partition.identifier = re.search(r'^(/dev/[a-zA-Z0-9]+)', line).group(0)
  except:
    pass

  try:
    partition.label = re.search(r'LABEL="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.uuid = re.search(r'UUID="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.type = re.search(r'TYPE="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  partitions.add(partition)

What you are looking for is anti-pythonic, because: 您正在寻找的是反Python的,因为:

The Zen of Python, by Tim Peters 提姆·彼得斯(Tim Peters)撰写的《 Python之禅》
Beautiful is better than ugly. 美丽胜于丑陋。
Explicit is better than implicit. 显式胜于隐式。
Simple is better than complex. 简单胜于复杂。
Complex is better than complicated. 复杂胜于复杂。
Flat is better than nested. 扁平比嵌套更好。
Sparse is better than dense. 稀疏胜于密集。
Readability counts. 可读性很重要。
Special cases aren't special enough to break the rules. 特殊情况还不足以打破规则。
Although practicality beats purity. 尽管实用性胜过纯度。
Errors should never pass silently. 错误绝不能默默传递。
Unless explicitly silenced. 除非明确地保持沉默。
In the face of ambiguity, refuse the temptation to guess. 面对模棱两可的想法,拒绝猜测的诱惑。
There should be one-- and preferably only one --obvious way to do it. 应该有一种-最好只有一种-显而易见的方法。
Although that way may not be obvious at first unless you're Dutch. 尽管除非您是荷兰人,否则一开始这种方式可能并不明显。
Now is better than never. 现在总比没有好。
Although never is often better than right now. 虽然从未往往比现在更好。
If the implementation is hard to explain, it's a bad idea. 如果实现难以解释,那是个坏主意。
If the implementation is easy to explain, it may be a good idea. 如果实现易于解释,则可能是个好主意。
Namespaces are one honking great idea -- let's do more of those! 命名空间是一个很棒的主意-让我们做更多这些吧!

In your case, I would use something like this: 在您的情况下,我将使用以下方式:

match = re.search(r'^(/dev/[a-zA-Z0-9]+)', line)
if match:
    partition.identifier = match.group(0)

And you have 3 lines instead of 4. 而且您有3行而不是4行。

There is no better way. 没有更好的办法。 Silently ignoring error is bad practice in any language, so it's naturally not Pythonic. 沉默地忽略错误在任何语言中都是不好的做法,因此它自然不是Pythonic。

Please don't ask for Python to be like PHP. 请不要要求Python像PHP。 You should always explicitly trap the most specific error you can. 您应该始终明确地捕获可能出现的最具体的错误。 Catching and ignoring all errors like that is not good best practice. 捕获并忽略所有此类错误不是最佳的最佳实践。 This is because it can hide other problems and make bugs harder to find. 这是因为它可以隐藏其他问题并使错误更难发现。 But in the case of REs, you should really check for the None value that it returns. 但对于RE,您应该真正检查它返回的None值。 For example, your code: 例如,您的代码:

label = re.search(r'LABEL="((?:[^"\\]|\.)*)"', line).group(1)

Raises an AttributeError if there is not match, because the re.search returns None if there is no match. 如果不匹配,则引发AttributeError,因为如果不匹配,则re.search返回None。 But what if there was a match but you had a typo in your code: 但是,如果有匹配项但您的代码中有错字怎么办:

label = re.search(r'LABEL="((?:[^"\\]|\.)*)"', line).roup(1)

This also raises an AttributeError, even if there was a match. 即使存在匹配,这也会引发AttributeError。 But using the catchall exception and ignoring it would mask that error from you. 但是使用catchall异常并忽略它会掩盖您的错误。 You will never match a label in that case, and you would never know it until you found it some other way, such as by eventually noticing that your code never matches a label (but hopefully you have unit tests for that case...) 在这种情况下,您永远不会匹配标签,直到找到其他方式,您才知道它,例如最终注意到代码从未与标签匹配(但希望您有针对这种情况的单元测试...)

For REs, the usual pattern is this: 对于RE,通常的模式是这样的:

matchobj = re.search(r'LABEL="((?:[^"\\]|\.)*)"', line)
if matchobj:
    label = matchobj.group(1)

No need to try and catch an exception here since there would not be one. 此处无需尝试捕获异常,因为不会有异常。 Except... when there was an exception caused by a similar typo. 除了...由于类似的错字引起异常时。

Use data-driven design instead of repeating yourself. 使用数据驱动的设计,而不是重复自己。 Naming the relevant group also makes it easier to avoid group indexing bugs: 命名相关组还可以更轻松地避免组索引错误:

_components = dict(
  identifier = re.compile(r'^(?P<value>/dev/[a-zA-Z0-9]+)'),
  label = re.compile(r'LABEL="(?P<value>(?:[^"\\]|\\.)*)"'),
  uuid = re.compile(r'UUID="(?P<value>(?:[^"\\]|\\.)*)"'),
  type = re.compile(r'TYPE="(?P<value>(?:[^"\\]|\\.)*)"'),
)

for line in blkid:
    line = line.strip()
    partition = Partition()

    for name, pattern in _components:
        match = pattern.search(line)
        value = match.group('value') if match else None
        setattr(partition, name, value)

    partitions.add(partition)

Building upon Gabi Purcanu's answer and your desire to condense to one-liners, you could encapsulate his solution into a function and reduce your example: 基于加比·普尔卡努(Gabi Purcanu)的回答以及您希望凝聚成一线的想法,您可以将其解决方案封装到一个函数中,并简化示例:

def cond_match(regexp, line, grp):
    match = re.search(regexp, line)
    if match:
        return match.group(grp)
    else:
        return None

for line in blkid:
    line = line.strip()
    partition = Partition()
    partition.identifier = cond_match(r'^(/dev/[a-zA-Z0-9]+)', line, 0)
    partition.label = cond_match(r'LABEL="((?:[^"\\]|\\.)*)"', line, 1)
    partition.uuid = cond_match(r'UUID="((?:[^"\\]|\\.)*)"', line, 1)
    partition.type = cond_match(r'TYPE="((?:[^"\\]|\\.)*)"', line, 1)
    partitions.add(partition)

There is warnings control in Python - http://docs.python.org/library/warnings.html Python中有警告控件-http: //docs.python.org/library/warnings.html

After edit: 编辑后:

You probably want to check if it is not None before trying to get the groups. 您可能想在尝试获取组之前检查它是否不是None Also use len() on the groups to see how many groups you have got . 还可以在组上使用len()来查看有多少组 "Pass"ing the error is definitely not the way to go. 错误“通过”绝对不是要走的路。

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

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