If you know the variable names beforehand, and they are constant, then you can do both these things in a different way:
getattr(c, 'var')
This is a shorthand for:
try:
return c.var
except AttributeError:
if have_default: # hand-wavey "more to this" for a later lesson
return default
raise
and
globals()['i'] = 25
is a nasty way of doing
global i
i = 25
The method you've given is essentially reaching into the internals and fiddling around with them. using the global
keyword is the better way to declare that you are use a variable in the global scope, because when the function is interpreted python knows that the variable is from a different scope at that point.
However if you don't know the name of the variable beforehand, then you'd be forced to do it the way in your examples. (but please, please think twice before using the globals
one. Putting arbitrary variables in a module's global namespace at runtime? *shudders*)