1

When using ctypes with libraries I'm not familiar with (in this specific case, Windows API), I tend to be really aggressive with checking each little step for failures since the Windows API simply returns Null, rather than throwing any kind of error.

So, I have tons of lines that look like this:

myVariableName = windll.user32.SomeWinAPIFuncThatReturnsZeroIfItFails()
if not myVariableName: print "Failed to create myVariableName"

And I repeat that a kazzilion times while figuring out the code.

It would be really nice if I could wrap the above check into a checkSuccess() function, which would simply take the name of the variable to check.

Something along the lines of

def check_success(var_name):
    if not var_name:
        print "failed to create %s" % var_name # <-- but the actual variable name; not the value
        sys.exit()
    return True

Of course, I could just manually pass in a string of the variable name, but for cleanliness and boilerplate's sake, it'd be cool it I could just pass in the single variable name.

Hopefully that makes sense!

Zack Yoshyaro
  • 2,056
  • 6
  • 24
  • 46
  • Please see for more help: http://stackoverflow.com/questions/932818/retrieving-a-variables-name-in-python-at-runtime – caranmegil Sep 10 '13 at 15:48
  • Consider using [`errcheck`](http://docs.python.org/2/library/ctypes.html#ctypes._FuncPtr.errcheck) to simplify your error checking. – nneonneo Sep 10 '13 at 15:51
  • What if my code is `somecollection[someindex] = windll.user32.SomeWinAPIFunc()`? Often a value doesn't have a name – Eric Sep 10 '13 at 15:53

2 Answers2

2

Are tracebacks enough for you here?

myVariableName = windll.user32.SomeWinAPIFuncThatReturnsZeroIfItFails()
if not myVariableName: raise ValueError

When that gets raised, you see:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    my_function()
  File "main.py", line 3, in my_function
    if not myVariableName: raise ValueError
ValueError

You could write a function to help you this:

def verify_non_zero(x):
    if x == 0: raise ValueError
    return x

And then:

myVariableName = verify_non_zero(windll.user32.SomeWinAPIFunc())

Which would give you the traceback:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    myVariableName = verify_non_zero(windll.user32.SomeWinAPIFunc())
  File "<pyshell#6>", line 2, in verify_non_zero
    if x == 0: raise ValueError
Eric
  • 95,302
  • 53
  • 242
  • 374
1

The short and sweet is: you can't (really) pass variables, only values. To pass a variable, you'd have to pass its name and its context.

This usually means that you already know the name, so you can just pass the name, or refer to the variable directly.

In your actual usecase, you're actually just checking the value, as far as I can tell. You can pass that value to a function, no problem (and pass the name as well, if you want - you know the name statically).

Marcin
  • 48,559
  • 18
  • 128
  • 201