2

Here's an example on what I'm thinking:

def check_args():
    if len(sys.argv) < 2:
        sys.exit('Reason')
    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: Folder %s was not found!' % sys.argv[1])
    global path
    path = sys.argv[1]

As you can tell after check_args() completes succefully the "path" variable has universal meaning - you can use it in other functions as de-facto variable.

So I'm thinking if there is a way to access "path" e.g. check_args.path?

How about in python v3?

3
  • 2
    This might just be an example, but if this is close to your actual code, you might want to look into a commandline parsing library (argparse is the most recent one to be included with python). Commented Jun 15, 2012 at 19:19
  • You don't have to put the code into a function. Just define a global path variable by defining it somewhere near the top of your module. You can store it as an attribute of a function as in @lanzz's answer, but that's almost the same thing since your function is a global module object. Commented Jun 15, 2012 at 19:24
  • Is there a good reason for check_args not to simply return the value, and let the caller worry about where it is saved? Commented Jun 15, 2012 at 19:37

2 Answers 2

3

Python functions are objects. You can define whatever custom properties you want on them:

def a():
    a.test = 123

a()
a.test # => 123
Sign up to request clarification or add additional context in comments.

1 Comment

Needing attributes on functions is usually a sign of you wanting a class, possibly with __call__.
0

You can simply return the value

def check_args():
    if len(sys.argv) < 2:
        sys.exit('Reason')
    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: Folder %s was not found!' % sys.argv[1])
    path = sys.argv[1]
    return path

my_path = check_args()

or when using if __name__ ...:

if __name__ == '__main__':
    my_path = check_args()
    results = do_something(path)

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.