Import a file to namespace

  • Thread starter Pedro Machado Santa
  • Start date
P

Pedro Machado Santa

Hi all,

I'm really a newbie in Python, and I wanted to do a tricky thing. I
don't know if it is possible but my intention was: I have a package
(namely breve) and I want to alter (override?) some of it's functions
preserving the original library/package - in order if I update it, I
do not lose my "hacks".

Until now I was overriding the functions directcly on my script and
adding them to the package namespace, like this:

import testpackage

class testClass():
#...

testpackage.testClass = testClass


But this has a problem. If I wanna use that code over many files, I
have to update it manually on all of them every time I update my
"hack". I was thinking if it is possible to keep that code on a file -
namely testpackageaddon.py and import it on my work file so that by
doing that it will automatically override the classes. Like so:

import testpackage
import testpackageaddon

testpackage.testClass() #my hacked class defined on
testpackageaddon.py


And on testpackageaddon.py:

import testpackage

class testClass():
#...

testpackage.testClass = testClass


Any tips, ideas on how to do this?

Many thanks.

Pedro Machado Santa
 
J

Jeffrey Froman

Pedro said:
import testpackage

class testClass():
#...

testpackage.testClass =  testClass


This method should work fine. Modules are effectively singletons, so running
this code one time anywhere in your application will cause the changes to
appear in all references to the original module.


Jeffrey
 
P

Pedro Machado Santa

This method should work fine. Modules are effectively singletons, so running
this code one time anywhere in your application will cause the changes to
appear in all references to the original module.

Yhea. I got it now. :) It already works. I wasn't putting the module
on my working dir.

(I created the module testpackageaddon.py and I did the "override" on
it, then imported it after the import testpackage on my working
script.)

Thanks.

Pedro Machado Santa
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top