Python:类属性定义上的代码重复
我正在尝试用 python 实现一个简单的 ORM。我面临代码重复问题,但我不知道如何解决。 这是我的项目中的类的简化示例:
class Person:
TABLE_NAME = 'person'
FIELDS = [
('name', 'VARCHAR(50)'),
('age', 'INTEGER')
]
# CODE DUPLICATION: the two next lines shoudl be genereated with FIELDS not hard coded...
name: str
age: int
def __init__(self, **kwargs):
self.__dict__ = kwargs
@classmethod
def create_sql_table(cls):
# use TABLE_NAME and FIELDS to create sql table
pass
alice = Person(name='Alice', age=25)
print(alice.name)
如果我删除两行 name: str
和 age: int
我会丢失自动完成功能并收到 mypy 错误在打印行上(错误:人没有属性名称)
但是如果我保留它,则会出现代码重复(每个字段名称我写两次)。
有没有办法避免代码重复(例如通过使用 FIELDS 变量生成这两行)?
或者实现此类避免代码重复的另一种方法(没有 mypy 错误和自动完成丢失)?
I'm trying to implement a simple ORM in python. I'm facing a code duplication issue and I do not know how to solve it.
Here is a simplified example of a class in my project:
class Person:
TABLE_NAME = 'person'
FIELDS = [
('name', 'VARCHAR(50)'),
('age', 'INTEGER')
]
# CODE DUPLICATION: the two next lines shoudl be genereated with FIELDS not hard coded...
name: str
age: int
def __init__(self, **kwargs):
self.__dict__ = kwargs
@classmethod
def create_sql_table(cls):
# use TABLE_NAME and FIELDS to create sql table
pass
alice = Person(name='Alice', age=25)
print(alice.name)
If I remove the two lines name: str
and age: int
I lose auto-completion and I get a mypy error on the print line (Error: Person has no attribute name)
But If I keep it, I have code duplication (I write twice each field name).
Is there a way to avoid the code duplication (by generating this two lines using FIELDS variable for instance) ?
Or another way to implement this class that avoid code duplication (without mypy error and auto-completion loss) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用描述符:
现在我们可以为每个列类型创建专门化:
当您定义
Person
类时,我们可以使用列类型这将打印:
您可能还应该创建一个基
Model
类,其中包含__init__
和Person
的类方法code>您还可以扩展
Column
类以允许可为空的列并添加默认值。Mypy 不会抱怨,并且可以正确地将
Person.name
的类型推断为 str,将Person.age
推断为 int。You can use descriptors:
Now we can create specializations for each column type:
And when you define the
Person
class we can use the column typesThis prints:
You should probably also create a base
Model
class that contains the__init__
and the class method ofPerson
You can also extend the
Column
class to allow nullable columns and add default values.Mypy does not complain and can correctly infer the types for
Person.name
to str andPerson.age
to int.好吧,我最终得到了这个
并且
Ok, I ended up with that
And
在 Person 类中尝试在构造函数中添加数据类型
In the class Person try to add data type in constructor