modifying a standard module?

Ulli Horlacher framstag at rus.uni-stuttgart.de
Fri Feb 12 17:46:59 EST 2016


Matt Wheeler <m at funkyhat.org> wrote:

> > How can I substitute the standard module function tarfile.extractall() with
> > my own function?
> 
> import tarfile
> def new_extractall(self, *args, **kwargs):
>     print("I am a function. Woohoo!")
> 
> tarfile.TarFile.extractall = new_extractall

This is more easy than I could imagined :-)
It is in my Python notes, now.


> But bear in mind that that will change tarfile.extractall for every
> single module that imports it within the same python process. Is that
> really what you want?

Yes. I have no own modules. Just one program file.


> Is there a reason you can't subclass TarFile as others have suggested?

The reason: I have no ideas on classes :-}

Of course, I should have to learn about, but until now it was not necessary.
The other solutions in this thread are sufficent for me.

Meanwhile I have implemented the iterator function:

    taro.extractall(members=itar(taro),path=edir)

def itar(tar):
  for ti in tar:
    # minimal protection against dangerous file names
    # see http://bugs.python.org/issue21109#msg215656
    ti.name = subst(r'^(?i)([a-z]:)?(\.\.)?[/\\]','',ti.name)
    print('untar "%s"' % ti.name)
    yield ti
    

Perfekt solution for me :-)
Thanks to all.


> If you must patch the standard library tarfile module then I would
> suggest patching it to have an extra, default False, argument to
> enable your printing behaviour, so you don't risk messing up anyone
> else's use of it.

Yes, a good idea.


-- 
Ullrich Horlacher              Server und Virtualisierung
Rechenzentrum IZUS/TIK         E-Mail: horlacher at tik.uni-stuttgart.de
Universitaet Stuttgart         Tel:    ++49-711-68565868
Allmandring 30a                Fax:    ++49-711-682357
70550 Stuttgart (Germany)      WWW:    http://www.tik.uni-stuttgart.de/



More information about the Python-list mailing list