重构;列表中的任意表达式 [英] Refactoring; arbitrary expression in lists

查看:62
本文介绍了重构;列表中的任意表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



作为前一个帖子的继续,PyChecker消息,我有一个关于代码重构的问题

,下面的代码片段会导致:


As continuation to a previous thread, "PyChecker messages", I have a question
regarding code refactoring which the following snippet leads to:

runner.py:200:函数(detectMimeType)返回的次数过多(11)

该函数只是一个很长的否则 -if"条款,分支到不同的退货声明。怎么了?它只是一个可能难看的代码。建议?
runner.py:200: Function (detectMimeType) has too many returns (11)

The function is simply a long "else-if" clause, branching out to
different return statements. What''s wrong? It''s simply a "probably ugly
code" advice?



这也是建议。通常你使用函数的dict或其他一些结构来查找你想要做的事情。



That is also advice. Generally you use a dict of functions, or some other
structure to lookup what you want to do.




更具体地说,我的函数看起来像这样: br />

#-------------------------------------- ------------------------

def detectMimeType(filename):


extension = filename [-3:]

basename = os.path.basename(filename)


如果扩展名==" php":

return" application / x-php"

elif extension ==" cpp"或者extension.endswith(" cc"):

return" text / x-c ++ - src"

#etcetera

elif extension ==" xsl":

return" text / xsl"


elif basename.find(" Makefile")!= -1:

返回" text / x-makefile"

else:

引发NoMimeError

#----- -------------------------------------------------- -------

(如果MIME检测看起来像石器时代,不要打扰,这是暂时的,直到

PyXDG获得对XDG的支持mime type spec ..)


我现在想知道是否可以用更紧凑的方式写这个,比如

if-clause是否有必要?当然,目前的代码是有效的,但是

也许它可能更漂亮。


我正在考虑嵌套列表的行,但是什么是我的障碍

是test和return语句都是简单的表达式;不是
函数或特定数据类型。任何想法?

干杯,


Frans



More specifically, my function looks like this:

#--------------------------------------------------------------
def detectMimeType( filename ):

extension = filename[-3:]
basename = os.path.basename(filename)

if extension == "php":
return "application/x-php"

elif extension == "cpp" or extension.endswith("cc"):
return "text/x-c++-src"
# etcetera
elif extension == "xsl":
return "text/xsl"

elif basename.find( "Makefile" ) != -1:
return "text/x-makefile"
else:
raise NoMimeError
#--------------------------------------------------------------
(don''t bother if the MIME detection looks like stone age, it''s temporary until
PyXDG gets support for the XDG mime type spec..)

I''m now wondering if it''s possible to write this in a more compact way, such
that the if-clause isn''t necessary? Of course, the current code works, but
perhaps it could be prettier.

I''m thinking along the lines of nested lists, but what is the obstacle for me
is that both the test and return statement are simple expressions; not
functions or a particular data type. Any ideas?
Cheers,

Frans

推荐答案

Frans Englich < FR *********** @ telia.com>在留言中写道

新闻:ma ************************************ ** @ pyth on.org ...
"Frans Englich" <fr***********@telia.com> wrote in message
news:ma**************************************@pyth on.org...

作为前一个帖子的继续,PyChecker消息,我有一个关于代码重构的
问题,下面的代码片段导致:

As continuation to a previous thread, "PyChecker messages", I have a question regarding code refactoring which the following snippet leads to:
runner.py:200:函数(detectMimeType)有太多的返回值(11)

该函数只是一个很长的否则 - 如果条款,分支到不同的退货声明。怎么了?它只是一个可能是
丑陋的代码。建议?
runner.py:200: Function (detectMimeType) has too many returns (11)

The function is simply a long "else-if" clause, branching out to
different return statements. What''s wrong? It''s simply a "probably ugly code" advice?



这也是建议。通常你使用函数的dict,或者一些
的其他结构来查找你想要做的事情。



That is also advice. Generally you use a dict of functions, or some other structure to lookup what you want to do.



更具体地说,我的函数看起来像这样:

#---------------------------------------------- ----------------
def detectMimeType(filename):

extension = filename [-3:]
basename = os。 path.basename(filename)

如果extension ==" php":
return" application / x-php"

elif extension ==" CPP"或者extension.endswith(cc):
返回" text / x-c ++ - src"
#etcetera



More specifically, my function looks like this:

#--------------------------------------------------------------
def detectMimeType( filename ):

extension = filename[-3:]
basename = os.path.basename(filename)

if extension == "php":
return "application/x-php"

elif extension == "cpp" or extension.endswith("cc"):
return "text/x-c++-src"
# etcetera



< snip>


由于你的大多数测试都是相当直接的''扩展名'XYZ"

意味着mimetype" aaa / bbb"'',这听起来真的很像字典类型
需要
解决方案。不过,您可能有一些愿望做一些

依赖于订单的测试。这里有两个想法 - 第一个遍历

表达式和结果类型列表,另一个使用字典查找。


- Paul

导入os


extToMimeMap = [

(''" php"'','application / x-php"),

(''" cpp"或extension.endswith(" cc")''," text / x-c ++ - src"),

(' '" xsl"''," text / xsl"),

]


def detectMimeType1(filename):

extension = filename [-3:]

basename = os.path.basename(filename)


表示exp,mimetype在extToMimeMap中:

if eval(" extension ==" + exp):return mimetype


#在这里做其他非扩展相关的测试

if basename.find(" Makefile")!= -1:

return" text / x-makefile"

else:

提高NoMimeError

extToMimeDict = {

" php&q uot;:application / x-php,

" cpp":" text / x-c ++ - src",

" xsl":" ; text / xsl",

}


def detectMimeType2(filename):


extension = filename [ - 3:]

basename = os.path.basename(filename)


#检查直接扩展匹配

尝试:

返回extToMimeDict [扩展名]

除了KeyError:

pass


#做更复杂的扩展和其他非扩展相关测试

如果extension.endswith(" cc"):

返回extToMimeDict [" cpp"]

if basename.find(" Makefile" )!= -1:

返回" text / x-makefile"


引发NoMimeError


for detectMimeType in(detectMimeType1,detectMimeType2):

for s in(a.php,z.acc,Makefile,blork.xsl):

print s," - >",detectMimeType(s)


<snip>

Since the majority of your tests will be fairly direct ''extension "XYZ"
means mimetype "aaa/bbb"'', this really sounds like a dictionary type
solution is called for. Still, you might have some desire to do some
order-dependent testing. Here are two ideas - the first iterates over a
list of expressions and resulting types, the other uses a dictionary lookup.

-- Paul
import os

extToMimeMap = [
(''"php"'', "application/x-php"),
(''"cpp" or extension.endswith("cc")'', "text/x-c++-src"),
(''"xsl"'', "text/xsl"),
]

def detectMimeType1( filename ):

extension = filename[-3:]
basename = os.path.basename(filename)

for exp,mimetype in extToMimeMap:
if eval("extension=="+exp): return mimetype

# do other non-extension-related tests here
if basename.find( "Makefile" ) != -1:
return "text/x-makefile"
else:
raise NoMimeError
extToMimeDict = {
"php": "application/x-php",
"cpp": "text/x-c++-src",
"xsl": "text/xsl",
}

def detectMimeType2( filename ):

extension = filename[-3:]
basename = os.path.basename(filename)

# check for straight extension matches
try:
return extToMimeDict[extension]
except KeyError:
pass

# do more complex extension and other non-extension-related tests here
if extension.endswith("cc"):
return extToMimeDict["cpp"]

if basename.find( "Makefile" ) != -1:
return "text/x-makefile"

raise NoMimeError

for detectMimeType in (detectMimeType1, detectMimeType2):
for s in ("a.php","z.acc","Makefile","blork.xsl"):
print s,"->",detectMimeType(s)


我无法破坏2.4中的原始代码,如果我试试这个:

import os,sys

class NoMimeError(Exception):

pass


def detectMimeType(filename):


extension = filename [-3:]

basename = os.path.basename(filename)

if extension ==" php":

return" application / x-php"

elif extension ==" cpp"或者extension.endswith(" cc"):

返回" text / x-c ++ - src"

elif extension ==" 1":

返回''BlahBlah''

elif extension ==" 2":

返回''BlahBlah''

elif extension ==" 3":

return''BrahBlah''

elif extension ==" 4":

return' 'BlahBlah''

elif extension ==" 5":

return''BlahBlah''

elif extension ==" 6" ;:

返回''BlahBlah''

elif extension ==" 7":

返回''BlahBlah''
elif extension ==" 8":

return''BlahBlah''

elif extension ==" 9":

返回''BlahBlah''

elif extension ==" 10":

return''BlahBlah''

elif extension ==" 11":

返回''BlahBlah''
elif extension ==" 12":

return''BrahBlah''

elif extension ==" 13":

返回''BlahBlah''

elif extension ==" 14":

返回''BlahBlah''

elif extension ==" 15":

return''BlahBlah''

elif extension ==" 16":

return' 'BlahBlah''

elif extension ==" 17":

return''BrahBlah''

elif extension ==" 18" ;:

返回''BlahBlah''

elif extension ==" 19":

return''BlahBlah''
elif extension ==" 20":

返回''BlahBlah''


elif extension ==" xsl":

返回" text / xsl"

elif basename.find(" Makefile" )!= -1:

返回" text / x-makefile"

else:

引发NoMimeError

尝试:

print detectMimeType(r''c:\test.php'')

print detectMimeType(''c:\ test.xsl'')

打印detectMimeType(''c:\ test.xxx'')

除了例外,e:

print>> sys.stderr,''%s:%s''%(e .__ class __.__ name __,e)


我得到
I can not break the original code in 2.4, if I try this:
import os, sys
class NoMimeError(Exception):
pass

def detectMimeType( filename ):

extension = filename[-3:]
basename = os.path.basename(filename)
if extension == "php":
return "application/x-php"
elif extension == "cpp" or extension.endswith("cc"):
return "text/x-c++-src"
elif extension == "1":
return ''BlahBlah''
elif extension == "2":
return ''BlahBlah''
elif extension == "3":
return ''BlahBlah''
elif extension == "4":
return ''BlahBlah''
elif extension == "5":
return ''BlahBlah''
elif extension == "6":
return ''BlahBlah''
elif extension == "7":
return ''BlahBlah''
elif extension == "8":
return ''BlahBlah''
elif extension == "9":
return ''BlahBlah''
elif extension == "10":
return ''BlahBlah''
elif extension == "11":
return ''BlahBlah''
elif extension == "12":
return ''BlahBlah''
elif extension == "13":
return ''BlahBlah''
elif extension == "14":
return ''BlahBlah''
elif extension == "15":
return ''BlahBlah''
elif extension == "16":
return ''BlahBlah''
elif extension == "17":
return ''BlahBlah''
elif extension == "18":
return ''BlahBlah''
elif extension == "19":
return ''BlahBlah''
elif extension == "20":
return ''BlahBlah''

elif extension == "xsl":
return "text/xsl"

elif basename.find( "Makefile" ) != -1:
return "text/x-makefile"
else:
raise NoMimeError
try:
print detectMimeType(r''c:\test.php'')
print detectMimeType(''c:\test.xsl'')
print detectMimeType(''c:\test.xxx'')
except Exception, e:
print >> sys.stderr, ''%s: %s'' %(e.__class__.__name__, e)

I get

application / x-php

text / xsl

NoMimeError:
application/x-php
text/xsl
NoMimeError:




所以虽然字典解决方案好得多,但似乎没什么问题

你的代码是不是 - 或者我错过了什么?



So although the dictionary solution is much nicer nothing seems wrong
with your code as it is - or am I missing something?


2005年1月12日星期三18:56, wi **** **@hotmail.com 写道:
On Wednesday 12 January 2005 18:56, wi******@hotmail.com wrote:
我无法打破2.4中的原始代码,如果我试试这个:


[.. 。]

所以虽然字典解决方案更好,但是你的代码没有什么用 - 或者我错过了什么?
I can not break the original code in 2.4, if I try this:
[...]

So although the dictionary solution is much nicer nothing seems wrong
with your code as it is - or am I missing something?




不,目前的代码有效。我只是在看Python解决问题的很酷的方式。 (关于11回报的问题是来自

PyChecker的编码风格报告。)

干杯,


Frans


这篇关于重构;列表中的任意表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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