Jython - 这两个布尔语句做同样的事情吗?
我对 Python 相当陌生,但我认为我理解流控制是如何工作的。
我从 Jython github 在第 418
418: pkgname = globals.get('__package__')
419: if pkgname is not None:
420: if not pkgname and level > 0:
421: raise ValueError, 'Attempted relative import in non-package'
行第 419 行上的 pkgname is not None
与第 420 行上的 not pkgname
做同样的事情吗?如果是的话,为什么会有那个检查?
我正在阅读导入源代码,这样我就可以更好地理解系统,尽管这很小,但我觉得很奇怪。由于我仍在学习 Python,所以我不想把任何事情视为理所当然。
谢谢你!
I'm reasonably new to Python but I thought I understood how the flow control worked.
I'm pasting this from the Jython github at line 418
418: pkgname = globals.get('__package__')
419: if pkgname is not None:
420: if not pkgname and level > 0:
421: raise ValueError, 'Attempted relative import in non-package'
Does pkgname is not None
on line 419 do the same thing as not pkgname
on line 420? If it does, why would that check be there?
I'm reading the import source code so I can understand the system better and, though minor, this struck me as odd. As I'm still learning Python, I don't want to take anything for granted.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道
pkgname
的有效值是什么,但从技术上讲,not pkgname
可以测试任何falsy 值,例如None
,还有False
、0
、[]
、""
等。但是,globals.get()
只会返回None
如果globals()
字典键不存在,因此如果目的只是测试它,那么它确实是多余的。旁注:想知道为什么要通过阅读 Jython 代码库来学习 Python。我建议您首先使用参考 CPython 实现和文档,而不是代码库本身
I don't know what the valid values are for
pkgname
but technicallynot pkgname
could test for any falsy value, such asNone
, but alsoFalse
,0
,[]
,""
etc. However,globals.get()
will only returnNone
if theglobals()
dict key is absent so if the intention is only to test for that then it is indeed redundant.Side note: wonder why you're learning python via reading the Jython codebase. I suggest you start with using the reference CPython implementation and with the docs rather than the codebase itself
您是正确的,第二次检查是否不需要 pkgname,因此代码可以是
You are correct the second check for if not pkgname is not needed so the code can just be