1

UPDATED:

How can I use a function variable within nested function? I've simplified my problem in the following example:

def build():
    n = 1 # code to parse rpm package minor version from file
    f = min_ver(n) # update minor version
    return

def min_ver(n):
    n = 2 # this is defined by another process, not set intentionally
    s =  1 + n # still need the original value from build()
    return s

The actual use case is that I'm grabbing a parsed rpm package minor version value in ex1() from disk called 'n'. When ex2() is executed from ex1(), it deletes the old package, builds a new rpm package with a new minor version. So when it calls for ex1()'s value within the nested function, it's not changed to the new version.

How can I maintain the original 'n' value within the nested function, before passing onto a new value of 'n' post nested function?

1
  • Nothing is going to change the local scope n within ex1 in the background. If you declare n as a global within ex1 then something else could change it externally. Commented Nov 29, 2018 at 2:05

2 Answers 2

2

A simple way to do this would be to pass the variable as an argument to ex2.

def build():
    n = int(1)
    f = ex2(n) # pass the value to the next function
    n = int(5) 
    return 

def min_ver(n_old):
    n = 2
    s =  1 + n_old # use the n that was passed in
    return s
Sign up to request clarification or add additional context in comments.

4 Comments

Can you not call ex2 before the background task changes n instead? Otherwise you could save the old n to a new variable before it is changed.
As in my updated answer - if you name the argument to min_ver something else, then it will retain that value even if you change n.
Somethings I over complicate things in my head, thank you.
Glad I could help, happens to all of us!
0

If you make ex2() actually nested then you can access the outer variables.

def ex1():
    n = int(1)
    def ex2():
        s =  1 + n
        return(s)
    f = ex2()
    n = int(5) # done with nested value, rewrite new value
    return()

Also, you probably want to return f or n instead of an empty tuple, I would imagine.

And you don't need to say int(1) you can just say 1. Everything, including integers and strings, is implicitly an object in python.

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.