According to Python documentation, both dir() (without args) and locals() evaluates to the list of variables in something called local scope. First one returns list of names, second returns a dictionary of name-value pairs. Is it the only difference? Is this always valid?
assert dir() == sorted( locals().keys() )
The output of
dir()when called without arguments is almost same aslocals(), butdir()returns a list of strings andlocals()returns a dictionary and you can update that dictionary to add new variables.Type:
Update or add new variables using
locals():using
dir(), however, this doesn’t work: