找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1601|回复: 0

[求助] 使用with open("/path/file.txt",'r') as时的enter和exit函数在哪定义

0

主题

2

帖子

2

积分

贫民

积分
2
asii2018 发表于 2018-10-17 21:57:02 | 显示全部楼层 |阅读模式
本帖最后由 asii2018 于 2018-10-17 22:01 编辑

刚接触python 自学了一段时间 使用pycharm ide 在练习with as时有个疑问

with open('TestDict.py','r') as fileDict:           //
    print(type(fileDict))
    print("fileDict line count = ",fileDict.readlines().__len__())

输出如下:


<class '_io.TextIOWrapper'>
fileDict line count =  9

背景:
with as 的语法是需要定义__enter__ 和 __exit__才会自动执行
所以我猜测 应该在open打开的流的父类中可以找到 enter和exit方法 里面有打开文件和关闭文件的定义
于是我找到TextIOWrapper 没有定义 他的父类io.TextIOBase 没有定义
_io._TextIOBase中没有定义 _TextIOBase没有定义

_IOBase中有写enter和exit方法 但是pass?
def __enter__(self, *args, **kwargs): # real signature unknown
pass
def __exit__(self, *args, **kwargs): # real signature unknown
pass
why?


后来发现竟然有三个TextIOWrapper 分别来自与 io.py  _io.py _pyio.py


最终在_pyio.py中找到close和open的实现def __enter__(self):
# That's a forward reference
    """Context management protocol.  Returns self (an instance of IOBase)."""
self._checkClosed()
    return self

def __exit__(self, *args):
    """Context management protocol.  Calls close()"""
self.close()

疑问:
1.为什么ide引导我去看<class '_io.TextIOWrapper'> _io模块的TextIOWrapper? 而不是直接_pyio模块的?
2.io.py  _io.py _pyio.py这三个模块有什么关联?他们的关联定义在哪个文件?







回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表