Python Forum

Full Version: list of user's variables in the interpreter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi,
i would like to ask how could i put a line of code that prints just user's declared variables in a function so it can be reused in a different scripts?

the code line is:
 [val for val in dir() if val.strip('__') == val] 
this code line executed directly in to the interactive mode of the python3 interpreter ( of some ide ) works perfectly:
 >>> [val for val in dir() if val.strip('__') == val]
['a'] 
the problems begin when the following procedure has been executed in some ide.

1. put the code line '[val for val in dir() if val.strip('__') == val]' in a separate function called 'u' - done
the 'u'-function looks like this:
def u ():
		a = [val for val in dir() if val.strip('__') == val] 
		return a   
2. put the function 'u' in a python-file called 'ud.py' - done

3. open the 'ud.py' in the ide - done

4. open python3 interpreter of the ide in interactive mode - done

5. import 'ud.py' like a module 'ud' by:
 >>> import ud  
- done

6. declare some variable:
a = 'ggfhgfjhh'  
- done

7. call the 'u'- function by:
>>> ud.u()  
- done

8. the output - an empty list:
 [ ]  
instead of
 ['a']  
how should i change the function 'u' so it can print just user's declared variables?

thanks in advance
As per the documentation,
Quote:dir() returns the list of names in the current local scope
what you are trying to do is get the same listing for different scopes.
Can't be done with this command.
If you want to access the parameter names of a function or the local variables defined in this function, the correct way is to use module inspect and attributes of code objects, for example:
>>> import inspect
>>> def spam(a, b, c='foo'):
...     bar = a + c
...     qux = [x for x in b if x.is_baz()]
... 
>>> spam.__code__.co_varnames
('a', 'b', 'c', 'bar', 'qux')
>>> s = inspect.signature(spam)
>>> s.parameters
mappingproxy(OrderedDict([('a', <Parameter "a">), ('b', <Parameter "b">), ('c', <Parameter "c='foo'">)]))
one possible solution could be to use the line [val for val in dir() if val.strip('__') == val] directly in to the
interactive mode of the interpreter just by coping and pasting it in to the interpreter or if the interpreter has
a history on the '->' button to scroll down and up with it.
If you only want the names in the main namespace you can use
# file ud.py
def u():
    import __main__
    return [w for w in dir(__main__) if w.strip('__') == w]
Then
>>> spam = 'eggs'
>>> ham = 3
>>> import ud
>>> ud.u()
['ham', 'spam', 'ud']
very nice and elegant solution! thanks a lot!