1

Consider following code:

##testing.py   
namespace = "original"
    def print_namespace():
       print ("Namespace is", namespace)

    def get_namespace_length(_str = namespace):
        print(len(_str))

##Main
import testing 
testing.namespace = "test"
testing.printnamespace()
testing.get_namespace_length()

print_namespace() return 'test' as exepcted, but the get_namespace_length() still return 8 which is the length of 'original'. How can I make get_namespace_length() taking the modified variable?

The use case of such implementation is some functions are used the same variable in the imported module, if I can modify/set variable, I can avoid explicitly to call out new variable in each function. Can someone advise?

Also, it doesn't have to be implemented in the way shown above, as long as it works. (global variable etc.)

1 Answer 1

1

Um... your default argument for get_namespace_length is database, undefined in your code snippet, also you switch from calling testing to test (I'm guessing that was one of many typos).

In short though, I believe its to do with how the bytecode is compiled in python. Arguments are 'preloaded', and therefore a change to a variable (such as namespace) does not get included in the compilation of get_namespace_length. If I remember correctly, upon import the entire code of the imported file is compiled and executed (try putting a print() statement at the end of testing.py to see)

So what you really want to do to obtain your length of 4 is change testing.py to:

namespace = "original"
def print_namespace():
    print ("Namespace is", namespace)

def get_namespace_length():
    _str = namespace
    print(len(_str))

Or just print(len(namespace)). Hope that helps!

Sign up to request clarification or add additional context in comments.

2 Comments

OMG.. can't believe I have so many typos, thanks for pointing it out, I have already update the question.
To you answer, thank you for all the details, your implementation would definitely work, but I still want to pass the 'namespace' in the function for flexibility. so, because of this 'pre-load' compilation in python, I think wrap the variables in a class with init is the best way to go? what do you think? thanks a lot!!!

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.