Jun-30-2020, 03:07 PM
in the latest testing iteration of this code, at line 83 i am trying to return a reference to a function named close which is defined in line 63. yet i get the message that it is not defined. what can cause this?
here is the output:
topen.py:
here is the output:
Output:lt2a/phil /home/phil 296> py trytopen.py
--------------------------------------------------- start0
CALLING open(*['foo0_6224721824273931', 'w'],**{}
CALLED __getattribute__ FOR ('write',)
CALLED __getattribute__ FOR ('write',)
CALLED __getattribute__ FOR ('close',)
Traceback (most recent call last):
File "trytopen.py", line 9, in <module>
f.close()
File "/home/phil/topen.py", line 83, in __getattribute__
return close
NameError: name 'close' is not defined
lt2a/phil /home/phil 297>
and here is the latest class code:topen.py:
# -*- coding: utf-8 -*- import io,os,sys,time _ofile = [] def _sep(): return '_'+str(int(time.time()*3906250)) class topen(): """Class for opening a file with temporary output name and automatic rename on close if write.""" # name is require by positional args or by keyword args # this class is like ztopen but without compression def __init__(self,*args,**kwargs): if args: args = list(args) fname = args.pop(0) if args: modes = args.pop(0) else: modes = kwargs.pop('mode',None) else: fname = kwargs.pop('file',None) modes = kwargs.pop('mode',None) if fname is None: raise('file is missing') if modes is None: raise('mode is missing') if 'x' in modes and isinstance(fname,(str,bytes)) and os.path.exists(fname): raise TypeError(f'{fname!r} refers to a name that already exists') fname = os.fspath(fname) if isinstance(fname,bytes): fname = ''.join(chr(x)for x in fname) if isinstance(modes,bytes): modes = ''.join(chr(x)for x in modes) if ('x' in modes or 'w' in modes) and isinstance(fname,str): rname = 1 oname = fname+_sep() else: rname = 0 oname = fname args = [oname,modes]+list(args) print(f'CALLING open(*{args!r},**{kwargs!r}',file=sys.stderr,flush=1) ofile = open(*args,**kwargs) if ofile is None: raise(f'failed to open file {oname!r}') _ofile[:0] = [ofile] self.rname = rname self.ofile = ofile self.oname = oname self.fname = fname self.closed = False def close(self): if self.rname: print(f'close {self.oname!r}',file=sys.stderr,flush=1) self.ofile.close() print(f'set closed flag True',file=sys.stderr,flush=1) self.closed = True print(f'rename {self.oname!r} to {self.fname!r}',file=sys.stderr,flush=1) return os.rename(self.oname,self.fname) else: print(f'close {self.oname!r}',file=sys.stderr,flush=1) self.closed = True return self.ofile.close() def __getattr__(self,*args): print(f'CALLED __getattr__ FOR {args!r}',file=sys.stderr,flush=1) return getattr(_ofile[0],*args) def __getattribute__(self,*args): print(f'CALLED __getattribute__ FOR {args!r}',file=sys.stderr,flush=1) if args[0] == 'close': return close return getattr(_ofile[0],*args)any ideas?