1

Suppose that I have a class like this one in a.py file:

class MyClass():
    def get(self, request, format='json'):
        pipeline = ['something_here']

How can I access the list pipeline from another file like b.py?
a.py and b.py are in the same directory.

I'm trying something like this:

from a import MyClass

my_list = MyClass.pipeline

OBS.: I can't change the a.py file because other people are using it.

igorkf
  • 3,159
  • 2
  • 22
  • 31
  • 1
    The list pipeline only exists during the method execution, before that its not created and after that its out of scope. If you need to access this list consider making it an attirbute of your class or class instance. – Chris Doyle Mar 24 '20 at 13:24
  • You can add `pipeline` as a function member, see [here](https://stackoverflow.com/questions/19326004/access-a-function-variable-outside-the-function-without-using-global/19327712) – Dani Mesejo Mar 24 '20 at 13:29

3 Answers3

3

You can't access it directly. What you could do is either return it, receive it as an attribute of the instance, or make it a global class variable.

A. Abramov
  • 1,823
  • 17
  • 45
2

As you can't change a.py, it is not possible to access this list. This list needs to be declared as a data member of MyClass or it needs to be returned from MyClass.get(). Otherwise, it is not possible

Moosa Saadat
  • 1,159
  • 1
  • 8
  • 20
1

One solution for this problem, is to use inheritance, and just change the logic for MyClass inside of a new class.

Given the following contents of a.py:

class MyClass:
    def __init__(self, x,y,z):
        self.x = x
        self.y = y
        self.z = z

    def get(self, somestring):
        pipeline = [somestring]
        return pipeline

Creating a new object of MyClass and calling get("somestring"), will return a list containing just that string. However, we do not set the property inside of the class, so it's only available inside of the method itself.

Creating a new file, in this case b.py, we can create a new class, inheriting from the first class, and just modify the get method to have the logic we want.

from a import MyClass

class MyNewClass(MyClass):
    def get(self, somestring):
        self.pipeline = [somestring]

Inside of b.py we can then do the following test:

old = MyClass(1,2,3)
print(old.x, old.y, old.z)
print(old.get("this is the input-string"))

new = MyNewClass(4,5,6)
print(new.x, new.y, new.z)
new.get("This is the second input-string")
print(new.pipeline)

Output:

1 2 3
['this is the input-string']
4 5 6
['This is the second input-string']
Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20