views:

54

answers:

2

I want to use imports inside a class that is then inherited by another class so that I don't have to manually define my imports in each file. I am trying it like this but its not working, any advice is appreciated:

class Djangoimports ():
    def __init__(self):
        from django.template import Context
        print Context


class Init1 (Djangoimports):
    def __init__(self):
        Djangoimports.__init__(self)

        self.c = Context(self.constructor_dict) # just example of trying to use the imported "Context"
>>>>> global name 'Context' is not defined

I have tried variations of trying to use "self" but can't figure out how to appropriately use this with the import from as its not the same as a class attribute / method where I normally use 'self'

+3  A: 

This works fine for me.

But you're better off doing this:

>>> class Test(object):
...        from functools import partial
... 
>>> Test().partial
<type 'functools.partial'>

Note that doing it your way, you have to initialize them on a per instance basis and assign to self, like so:

def Test(object):
    def __init__(self):
         from functools import partial
         self.partial = partial

either way, you can now access bar in other methods on that class or a derived one as self.bar.

aaronasterling
Thanks, I think I get what you mean, I'm not sure how I would use it within the class that inherits the importer class though
Rick
@Rick. You could just access it as `self.bar` because it becomes part of the classes namespace.
aaronasterling
oh ok, I see, should have caught that myself :)... thanks for your help in this
Rick
+1  A: 

In Python, an import just adds to current namespace. The namespace is lost once you return from the function, but you can preserve the pointer appending it to 'self'.

You can do:

class Djangoimports ():
    def __init__(self):
        from django.template import Context
        self.Context = Context

class Init1 (Djangoimports):
    def __init__(self):
        Djangoimports.__init__(self)
        self.c = self.Context(self.constructor_dict)
Paulo Scardine