i'd like to make an object that no matter what attribute name is requested (other than standard ones) a single specific value is given. one way this might be done is with a specific method of that object which is given the name of the requested attribute and returns the value to be given (which might be another method). similarly, i'd like a way to assign to any name. that would need 2 arguments or 2 items in a sequence.
one purpose might be an object that needs to proxy a variety of other objects.
Perhaps
3.3.2. Customizing attribute access > object.__getattr__(self, name) will do what you are after.
class SillyObject:
def __init__(self, some_attr):
self.some_attr = some_attr
def __getattr__(self, key):
return self.some_attr
silly_object = SillyObject('one attribute to rule them all')
print(silly_object.some_attr)
print(silly_object.not_real)
print(silly_object.anything)
Output:
one attribute to rule them all
one attribute to rule them all
one attribute to rule them all
that looks like exactly the thing that will do the job.
here is what i am trying to do:
# -*- coding: utf-8 -*-
import os,time
class output(IOBase):
def __init__(self,*args,**kwargs):
if len(args)!=2:
raise ValueError('file name (arg 1) and mode (arg 2) both required')
fn,md = args[:2]
if not isinstance(fn,_sbb):
raise TypeError('file name not a str or bytes')
if not isinstance(md,_sbb):
raise TypeError('file mode not a str or bytes')
if not 'w' in md:
raise ValueError('file mode is not for write')
tn = fn+'.'+str(int(time.time()*3906250))
self.tn,self.fn = tn,fn
self.f = open(tn,md,**kwargs)
def __getattr__(self,*args):
return getattr(self.f,*args)
def close(self):
self.f.close()
return os.rename(self.tn,self.fn)
i don't know if i've done this right. i've just thrown together some code to have something to try things with. many of my scripts do this. i've coded it so many times it is frustrating. i did see an existing class that did this, but it used the weak Unix temporary name logic (i have experienced a name collision with it several years ago).
i plan to add logic to check for '.xz' at the end of the file name and use lzma.open().