-2

I have code like this

def function3():
    print(text)

def function2():
    text = "Hello"
    function3()

def function1():
    text = "World"
    function3()

Like you see i want to automatically pass variable from function2 and function1 to function3. This variable should be visible only on this three functions (so I can't set it global). Also I don't want to pass this variable every time between round brackets, because I will use function3 thousands of times. Is there a something like keyword use in php?

function3() use (text):
    print(text)
2
  • 5
    So pass them in normally. "Explicit is better than implicit". I don't understand your reasoning. What is the difference between having function3() "thousands of times" and having function3(arg) "thousands of times" ? Commented Jun 1, 2020 at 9:47
  • Does this answer your question? How to share variable between functions in python? Commented Jun 1, 2020 at 9:50

2 Answers 2

1

I'm not 100% sure I now what you want to do (don't know php), but is it just something like this?

def function3(text):
    print(text)

def function2():
    text = "Hello"
    function3(text)

def function1():
    text = "World"
    function3(text)
Sign up to request clarification or add additional context in comments.

Comments

1

There is nothing directly equivalent, you would normally just pass the arguments around.

From what I understand, the use keyword in PHP to manually add variables to an anonymous function's closure. In python, function scopes already create closures for you automatically using lexical scoping rules. You can do something like this:

def function_maker():
    text = None # need to initialize a variable in the outer function scope
    def function3():
        print(text)

    def function2():
        nonlocal text
        text = "Hello"
        function3()

    def function1():
        nonlocal text
        text = "World"
        function3()

    return function1, function2, function3

function1, function2, function3 = function_maker()

But this pattern wouldn't be common in Python, you would just use a class:

class MyClass:
    def __init__(self, text): # maybe add a constructor
        self.text = text

    def function3(self):
        print(self.text)

    def function2(self):
        self.text = "Hello"
        self.function3()

    def function1(self):
        self.text = "World"
        self.function3()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.