0

这个代码可以优化吗?也许可以把它写得更短,让它更“pythonic”?

...
check_pass = 0

if key == 'media':
    size_check_pass = 0
    if some_check_func(xxx): size_check_pass = 1
    ...

    format_checks_pass = 0
    if...some_checks... : format_checks_pass = 1

    if size_check_pass and format_checks_pass: check_pass = 1

if key == 'text':
    line_end_check_pass = 0
    if (((some checks))): line_end_check_pass = 1

    lenght_check_pass = 0
    if len(file) < 1000: lenght_check_pass = 1

    if line_end_check and lenght_check_pass: check_pass = 1

if check_pass:
    ...

代码的背景是检查每种文件类型的不同条件。

4

3 回答 3

1

您也许可以将字典用作一种调度表。就像是

def media_checks(f): 
  ...
  return pass

def text_checks(f): 
  ...
  return pass

_dispatch = {}
_dispatch['media'] = media_checks
_dispatch['text'] = text_checks

dispatch_func = _dispatch[key]
check_pass = dispatch_func(your_file)

这会将您的代码拆分,因此更易于阅读和维护。它还隔离了用于检查单个函数中每种文件类型的代码。

于 2013-05-29T11:57:15.140 回答
0

首先,对于您的第一个if,您的代码会受到条件复杂性代码气味的影响。您可以通过inline method重构来解决:您不需要您的size_check_passformat_checks_pass布尔值,并且可以在最终的 if 语句中直接评估这两个条件,if ...some_checks... and some_check_func(xxx)而不是if size_check_pass and format_checks_pass. 这给了你

check_pass = 0

if key == 'media':

    if ...some_checks... and some_check_func(xxx): 
         check_pass = 1

然后,对第二个if也这样做。而且你不想检查key = 'text'你是否已经有了key = 'media',所以最后

check_pass = 0

if key == 'media':
    if some_check_func(xxx)and ...some_checks...: 
         check_pass = 1

else if key == 'text':
    if (((some checks)))and len(file) < 1000: 
         check_pass = 1

if check_pass:
...
于 2013-05-29T11:59:26.647 回答
0

所以你总是有一系列的检查。

首先,您可以缩短条件:

...
check_pass = False # to make it more boolean

if key == 'media':
    size_check_pass = some_check_func(xxx)
    format_checks_pass = ...result of your checks...
    check_pass = size_check_pass and format_checks_pass

if key == 'text':
    line_end_check_pass = (((some checks)))

    length_check_pass = len(file) < 1000

    check_pass = line_end_check and length_check_pass

if check_pass:
    ...

或进一步压缩它们:

...
check_pass = False # to make it more boolean

if key == 'media':
    check_pass = some_check_func(xxx) and ...result of your checks...

if key == 'text':
    check_pass = (((some checks))) and len(file) < 1000

if check_pass:
    ...

然后你可以应用一个类似于 jamesj 的系统,但可能使用条件表达式列表:

def some_checks():
  ...
  return True or False

def other_checks(f): 
  ...
  return ...

_dispatch = {
    'media': [lambda: some_check_func(xxx), some_checks],
    'text' : [other_checks, lambda: len(file) < 1000]
}

dispatch_list = _dispatch[key]
check_pass = all(func() for func in dispatch_list)
于 2013-05-29T16:53:07.270 回答