uilianries
uilianries

Reputation: 3887

How to get a variable from an outside function?

I would like to get a variable which contains dict with important values from another project, and it is in a function, for instance:

Foo is an external module, it's not part of my project.

# bar.py

def bar():
    qux = {"alpha": 1, "beta": 2, "charlie": 3}

I want to get qux value in my project:

# main.py
from foo.bar import bar

print(bar.qux)

But when I try to get directly, I receive:

ERROR: 'function' object has no attribute 'qux'

Is there any way to do this? I'm running Python 3.8.

Upvotes: 1

Views: 193

Answers (3)

Marc
Marc

Reputation: 1987

Use of self in the function is bad for 2 reasons. First, it is not being used and second it is confusing as self is the default Object Orientated syntax (classes).

To fix your function remove self and return your value:

def bar():
    return {"alpha": 1, "beta": 2, "charlie": 3}

But I think you want something OO, so wrap it in a class:

class Foo:

    def bar(self):
        self.qux = {"alpha": 1, "beta": 2, "charlie": 3}

foo = Foo()
foo.bar() 
foo.qux

But that is bad practice as an __init__ should be used:

class Foo:

    # qux = None also an option, but I recommend __init__

    def __init__(self):
        self.qux = None

    def bar(self):
        self.qux = {"alpha": 1, "beta": 2, "charlie": 3}

foo = Foo()
foo.bar() 
foo.qux

Or just go class style, common in model definitions and other Python fun:

class Foo:
    qux = {"alpha": 1, "beta": 2, "charlie": 3}
foo = Foo()
foo.qux
# will also work in this circumstance
Foo.qux

Upvotes: -1

alex067
alex067

Reputation: 3301

Well you're trying to get a variable that's declared inside a function, and treating it like its an object.

Just change:

def bar(self):
    qux = {"alpha": 1, "beta": 2, "charlie": 3}
    return qux

and then you can get the object inside bar as:

from foo.bar import bar

print(bar())

But this is just redundant; why declare an object inside a function, just to access it?

Inside your foo.py, you should just declare the object like normal and access it via:

from foo import qux

EDIT: Since you don't have access to foo, perhaps this answer is better suited:

How to get function object inside a function (Python)

Since all functions are objects in Python, this is technically possible.

Upvotes: 1

clubby789
clubby789

Reputation: 2733

You may be confusing functons with classes here. But to do this with minimal changes to your code, you'd want to do

# bar.py

def bar(self):
    return {"alpha": 1, "beta": 2, "charlie": 3}
# main.py
from foo.bar import bar

print(bar())

Upvotes: 1

Related Questions