Namespace issue

kyosohma at gmail.com kyosohma at gmail.com
Wed May 23 15:20:52 EDT 2007


On May 23, 1:20 pm, Ritesh Raj Sarraf <r... at researchut.com> wrote:
> 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.

The reason you can't put the import into the __init__ is that that is
also a method, so the imported module is only available to that
method's namespace. This is also true if you had put the import into
any other method.

The only way to make it global is to put your class into its own
module and put the import before the class creation.

Depending on how your instantiating the class, you may not need to
worry about the whole importing thing. If you have all your code like
this:

class something(obj):
  def __init__(self):
    #do something
  def grabData(self):
    # do something
    import module

x = something()
y = something()

Then the module gets imported only once. See
http://www.python.org/search/hypermail/python-1993/0342.html

I'm not sure what happens when you have one module calling another
module that import a third module though.

Mike




More information about the Python-list mailing list