views:

45

answers:

2

I find myself doing something like this constantly to pull GET args into vars:

some_var = self.request.get('some_var', None)
other_var = self.request.get('other_var', None)
if None in [some_var, other_var]:
    logging.error("some arg was missing in " + self.request.path)
    exit()

What I would really want to do is:

pull_args('some_var', 'other_var')

And that would somehow pull these variables to be available in current scope, or log an error and exit if not (or return to calling method if possible). Is this possible in Python?

+3  A: 

No it's not and also pointless. Writing to outer namespaces completely destroys the purpose of namespaces, which is having only the things around that you explicitly set. Use lists!

def pull_args(*names):
    return [self.request.get(name, None) for name in names]

print None in pull_args('some_var', 'other_var')

Probably this works too, to check if all _var are set:

print all(name in self.request for name in ('some_var', 'other_var'))
THC4k
+1  A: 

First, a disclaimer: "pulling" variables into the local scope in any way other than var = something is really really really not recommended. It tends to make your code really confusing for someone who isn't intimately familiar with what you're doing (i.e. anyone who isn't you, or who is you 6 months in the future, etc.)

That being said, for educational purposes only, there is a way. Your pull_args function could be implemented like this:

def pull_args(request, *args):
    pulled = {}
    try:
        for a in args:
            pulled[a] = request[a]
    except AttributeError:
        logging.error("some arg was missing in " + self.request.path)
        exit()
    else:
        caller = inspect.stack()[1][0]
        caller.f_locals.update(pulled)

At least, something to that effect worked when I came up with it probably about a year ago. I wouldn't necessarily count on it continuing to work in future Python versions. (Yet another reason not to do it) I personally have never found a good reason to use this code snippet.

David Zaslavsky
I was persuaded to use lists instead, but I am accepting this because it contained the answer I asked for.
Bemmu