为什么不呢inspect.getsource返回整个类源?

2024-09-30 03:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的forms.py中有以下代码:

from django import forms
from formfieldset.forms import FieldsetMixin


class ContactForm(forms.Form, FieldsetMixin):
    full_name = forms.CharField(max_length=120)
    email = forms.EmailField()
    website = forms.URLField()
    message = forms.CharField(max_length=500, widget=forms.Textarea)
    send_notification = forms.BooleanField(required=False)

    fieldsets = ((u'Personal Information',
                {'fields': ('full_name', 'email', 'website'),
                'description': u'Your personal information will not ' \
                                u'be shared with 3rd parties.'}),
                (None,
                {'fields': ('message',),
                'description': u'All HTML will be stripped out.'}),
                (u'Preferences',
                {'fields': ('send_notification',)}))

当我试图用inspect以编程方式提取代码时,它忽略了fieldsets

^{pr2}$

这似乎不是空行的问题。我在没有空白行的情况下进行了测试,并且在其他属性之间添加了空白行。结果不变。在

为什么inspect只返回fieldsets之前的部分而不是类的整个源?在


Tags: 代码namefromimportmessagefieldsemailforms
2条回答

编辑:根据评论进行修订:

inspect.getsource(forms.ContactForm)中,BlockFinder.tokeneater()方法用于确定ContactForm块的停止位置。除此之外,它还检查tokenize.DEDENT,它在存储在github的版本中的字段集之前找到它。该行只包含一个换行符,因此inspect认为当前块已结束。在

如果你插入4个空格,它对我再次有效。我无法解释这背后的理由,也许是表现。在

class ContactForm(forms.Form):
    full_name = forms.CharField(max_length=120)
    email = forms.EmailField()
    website = forms.URLField()
    message = forms.CharField(max_length=500, widget=forms.Textarea)
    send_notification = forms.BooleanField(required=False)
    # <  insert 4 spaces here
    fieldsets = ((u'Personal Information',
                {'fields': ('full_name', 'email', 'website'),
                'description': u'Your personal information will not ' \
                                u'be shared with 3rd parties.'}),
                (None,
                {'fields': ('message',),
                'description': u'All HTML will be stripped out.'}),
                (u'Preferences',
                {'fields': ('send_notification',)}))

inspect.getsource(forms)工作方式不同的原因是,在这种情况下,inspect不必确定类定义的开始和结束。它只是输出整个文件。在

对我有用。我没有“来自”窗体字段集.forms在我的代码中导入FieldsetMixin。也许这是个问题。。在

相关问题 更多 >

    热门问题