0

I'm currently working on a simple file transfer program in Python. I am having trouble with the function for prompting the user for the location of the folder to be copied.

def getSrc():
    if getSrc.has_been_called is False:
        source = askdirectory()
        getSrc.has_been_called = True
        return source
    else:
        return source

getSrc.has_been_called = False

The variable source comes up as an unresolved reference. I understand that the variable must be initialized again due to the scope of an if-else statement, but I am unsure of how to save the directory in the source variable without the user being prompted for the directory again.

1
  • though Kevin's answer is a good fit for you, what you want is actually typical singleton pattern. employing design pattern will make your code clearer, especially when you are working with others. try to make it a serious singleton instance, that would help. Commented Jun 17, 2015 at 20:07

1 Answer 1

1

When you call getSrc a second time, the value of source that was created the first time has long since gone out of scope and been garbage collected. To prevent this, try making source an attribute of the function the same way you did for has_been_called.

def getSrc():
    if getSrc.has_been_called is False:
        getSrc.source = askdirectory()
        getSrc.has_been_called = True
        return getSrc.source
    else:
        return getSrc.source

Although, it's a bit messy to have two attributes when you can make do with one:

def getSrc():
    if not getSrc.source:
        getSrc.source = askdirectory()
    return getSrc.source
getSrc.source = None

If you're in a higher-order functional mood, it may be worthwhile to create a function that memoizes other functions. You can look at PythonDecoratorLibrary for some tips on doing that, or you can just use one already prepared by Python

import functools

@functools.lru_cache()
def getSrc():
    return askdirectory()
Sign up to request clarification or add additional context in comments.

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.