-2

For example

class c:
    var = 15

getattr(c, 'var')

or

i = 0
globals()['i'] = 25

why here our variable writing like string type. I saw this in some built-in functions and in Django and i think this make code much difficulty for understanding isn't it?

deceze
  • 510,633
  • 85
  • 743
  • 889
Hman
  • 11
  • 6
  • Well, yeah, in these particular examples there's certainly a simpler way to do it. But `getattr` and `globals` has its uses if you're trying to work with unknown attributes/variables and/or set them dynamically. – deceze Oct 16 '17 at 14:56
  • what else would you like the **name** of a variable to be? – Ma0 Oct 16 '17 at 14:56
  • These approaches have their use, but yes, generally using dynamic variables makes code harder to understand – juanpa.arrivillaga Oct 16 '17 at 14:57

2 Answers2

0

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*)

Andrew Gelnar
  • 633
  • 4
  • 14
0

globals() returns a dictionary, so you have to use the variable name as string for looking at it. In globals()['var'], 'var' is just a key in globals() returned dict, so it must be given as string.

getattr(c, 'var') looks for attribute "var" in c.__dict__.

Remember: Python makes a heavy us of dicts.

lpozo
  • 598
  • 2
  • 9