为什么不inspect.getsource返回全班源?
-
06-09-2019 - |
题
我有这样的代码在我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
:
In [1]: import inspect
In [2]: import forms
In [3]: print inspect.getsource(forms)
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',)}))
In [4]: print inspect.getsource(forms.ContactForm)
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)
In [5]:
这似乎不与空行的问题。我之间没有空行测试,我已经把额外的空白行中其他属性之间。结果并没有改变。
为什么检查任何想法是只返回fieldsets
之前的部分,而不是类的整个源代码?
解决方案
修改:订正基于评论强>
内部inspect.getsource(forms.ContactForm)
方法BlockFinder.tokeneater()
被用来确定ContactForm
块停止在那里。除了别人,它会检查tokenize.DEDENT
,它存放在GitHub上在您的版本的fieldsets前右认定。行只包含一个线断裂,所以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
在这种情况下没有确定类定义的开始和结束。它简单地输出整个文件。
其他提示
我的作品。我没有在我的代码“从formfieldset.forms导入FieldsetMixin”。也许这是造成问题..
不隶属于 StackOverflow