首页
学习
活动
专区
圈层
工具
发布

OOP重构
EN

Code Review用户
提问于 2021-08-23 01:51:07
回答 1查看 168关注 0票数 0

以下脚本从不同的文件格式派生架构。能给我看一下这个吗?这些改进是什么样子的:

代码语言:javascript
复制
    def _null_allowed_in_cols(self):
        for field in self.fields:
            field["type"] = self._field_type_converter(field["type"])
            if type(field["type"]) == list:
                if "null" not in field["type"]:
                    field["type"].insert(0, "null")
            else:
                field["type"] = ["null", field["type"]]

    def _field_type_converter(self, field_type) -> Union[str, list]:
        if type(field_type) is dict or type(field_type) is avro.schema.ImmutableDict:
            return field_type["type"]
        elif type(field_type) is list:
            return list(map(lambda x: self._field_type_converter(x), field_type))
        else:
            return field_type
EN

回答 1

Code Review用户

回答已采纳

发布于 2021-08-23 16:09:42

_col_type

您可以在这里使用生成器表达式返回第一个匹配项或None

代码语言:javascript
复制
    # go from this
    def _col_type(self, column_name):
        for column in self.fields:
            if column["name"] == column_name:
                return column
        return None

   # to this
   def _col_type(self, column_name):
       return next((
        col['name'] for col in self.fields if col['name'] == column_name
       ), None)

检查类型

使用isinstance而不是type(val) == cls

代码语言:javascript
复制
# instead of this
if type(field["type"]) == list:
    # do something
# or this
if type(val) is dict:
    # do something

# do this instead
if isinstance(field['type'], list):
    # do something

# or
if isinstance(field_type, (dict, avro.schema.ImmutableDict)):
    # do something

何时使用lambda与函数

在本声明中:

代码语言:javascript
复制
list(map(lambda x: self._field_type_converter(x), field_type))

你其实不需要兰布达:

代码语言:javascript
复制
list(map(self._field_type_converter, field_type))
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/266308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档