Namespace issue

R

Ritesh Raj Sarraf

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
 

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,770
Messages
2,569,583
Members
45,072
Latest member
trafficcone

Latest Threads

Top