Namespace issue

Ritesh Raj Sarraf rrs at researchut.com
Wed May 23 14:20:01 EDT 2007


Hi,

I need a little help in understanding how Namespaces and scoping works with
Classes/Functions in Python.

Here's my code:
class FetchData:
    def __init__(self, dataTypes=["foo", "bar", "spam"], archive=False):
        
        self.List = []
        self.Types = dataTypes
        
        if archive:
            self.Archiver = Archiver(True)
        
    def FetchData(self, PackageName, Filename=None):
        
        try:
            import my_module
        except ImportError:
            return False
        
        if Filename != None:
            try:
                file_handle = open(Filename, 'a')
            except IOError:
                sys.exit(1)
        
        (amnt, header, self.List) = my_module.get_data(PackageName)


This is the only way this code will work.

As per my understanding, the bad part is that on every call of the method
FetchData(), an import would be done.

To not let that happen, I can put the import into __init__(). But when I put
in there, I get a NameError saying that my_module is not available even
though it got imported.
All I noticed is that the import has to be part of the method else I end up
getting a NameError. But always importing my_module is also not good.

What is the correct way of doing this ?
IMO, ideally it should be part of __init__() and be imported only when the
class is instantiated.

Thanks,
Ritesh
-- 
If possible, Please CC me when replying. I'm not subscribed to the list.




More information about the Python-list mailing list