How to get user defined variable in Python? [duplicate] - python

This question already has answers here:
List user defined variables, python
(5 answers)
Closed 6 years ago.
This have been searched on Google and on Stack-Overflow, before asking the question, without success. Hence, this is not a trivial question...
I have two modules : Main and module1 and am doing this code in Main :
import module1
dict1= module1.getdict_userdefinedvariable()
dict1 is then manipulated in a programmatic way to check (assertion, validation,..).
However, if in getdict_userdefinedVariable(), I am using Globals() or Vars(),
I have access ONLY to the variables defined in the sub-module.
Also, Globals(), Vars() or Ipython who_ls gives the list of all names including user-defined module names, user-defined function names.
So,How can we get variables defined in Main module and filter only user-defined variables by removing USER defined module, USER defined function names ?
There is
who_ls in ipython,
but it contains module and function names....

Does not this really work for You? I tried - got my vars listed:
All credits to Niek de Klein, this is his answer from:
List user defined variables, python
If you don't put any underscores in front of your variables you could do:
#!/us/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"
for name in dir():
if not name.startswith('__'):
myvalue = eval(name)
print name, "is", type(myvalue), "and is equal to ", myvalue

Related

List user defined variables from a parent module (Python 3)

I have a function within a module that lists defined variables
Simplified Example:
for var_name in globals():
if not var_name.startswith('__'):
var_value = eval(var_name)
var_type = type(var_value)
print(var_name, "is", var_type, "and is equal to ", var_value)
This works when I run it from within the origin module, but not when the module is imported to another script. It only ever reads the variables defined in the origin module.
I also tried:
import __main__
for var_name in __main__.__dict__:
But that didn't work either. How can I get this function to work when imported into another script?
Thanks!
You mean to use __main__.__dict__, not __main__.dict. That, with some minor loop modifications (i.e. eval will not work as you want it to in this context, instead use __main__.__dict__[var_name]) should get your code working.

Getting name of a variable in Python [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 4 months ago.
If I have local/global variable var of any type how do I get its name, i.e. string "var"? I.e. for some imaginary function or operator nameof() next code should work:
var = 123
assert nameof(var) == "var"
There's .__name__ property for getting name of a function or a type object that variable holds value of, but is there anything like this for getting name of a variable itself?
Can this be achieved without wrapping a variable into some magic object, as some libraries do in order to get variable's name? If not possible to achieve without magic wrappers then what is the most common/popular wrapping library used for this case?
You can do this with the package python-varname: https://github.com/pwwang/python-varname
First run pip install varname. Then see the code below:
from varname import nameof
var = 123
name = nameof(var)
#name will be 'var'
For Python 3.8 and later, you can try this not-so-pretty way, but it works for any python object that has a str-method:
var = 123
var_name = f'{var=}'.partition('=')[0]
def get_veriable_name(variable):
current_file = os.path.basename(__file__)
with open(current_file, "r") as f:
for line in f:
if variable in line:
return line.split("=")[0].strip()
return None

using __init__.py for import results in NameError: name '...' is not defined [duplicate]

I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using from a import *.
So instead of typing
a.sayHi()
a.sayBye()
I can say
sayHi()
sayBye()
which I find simplifies things a great deal. Now, say I have a bunch of variables that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use import a and then be required to prefix all my variables with a..
The following situation would by ideal:
a.py
name = "Michael"
age = 15
b.py
some_function
if name == "Michael":
if age == 15:
print("Simple!")
Output:
Simple!
You gave the solution yourself: from a import * will work just fine. Python does not differentiate between functions and variables in this respect.
>>> from a import *
>>> if name == "Michael" and age == 15:
... print('Simple!')
...
Simple!
Just for some context, most linters will flag from module import * with a warning, because it's prone to namespace collisions that will cause headaches down the road.
Nobody has noted yet that, as an alternative, you can use the
from a import name, age
form and then use name and age directly (without the a. prefix). The from [module] import [identifiers] form is more future proof because you can easily see when one import will be overriding another.
Also note that "variables" aren't different from functions in Python in terms of how they're addressed -- every identifier like name or sayBye is pointing at some kind of object. The identifier name is pointing at a string object, sayBye is pointing at a function object, and age is pointing at an integer object. When you tell Python:
from a import name, age
you're saying "take those objects pointed at by name and age within module a and point at them in the current scope with the same identifiers".
Similarly, if you want to point at them with different identifiers on import, you can use the
from a import sayBye as bidFarewell
form. The same function object gets pointed at, except in the current scope the identifier pointing at it is bidFarewell whereas in module a the identifier pointing at it is sayBye.
Like others have said,
from module import *
will also import the modules variables.
However, you need to understand that you are not importing variables, just references to objects. Assigning something else to the imported names in the importing module won't affect the other modules.
Example: assume you have a module module.py containing the following code:
a= 1
b= 2
Then you have two other modules, mod1.py and mod2.py which both do the following:
from module import *
In each module, two names, a and b are created, pointing to the objects 1 and 2, respectively.
Now, if somewhere in mod1.py you assign something else to the global name a:
a= 3
the name a in module.py and the name a in mod2.py will still point to the object 1.
So from module import * will work if you want read-only globals, but it won't work if you want read-write globals. If the latter, you're better off just importing import module and then either getting the value (module.a) or setting the value (module.a= …) prefixed by the module.
You didn't say this directly, but I'm assuming you're having trouble with manipulating these global variables.
If you manipulate global variables from inside a function, you must declare them global
a = 10
def x():
global a
a = 15
print a
x()
print a
If you don't do that, then a = 15 will just create a local variable and assign it 15, while the global a stays 10

Why is "from ... import *" in a function not allowed? [duplicate]

This question already has answers here:
Python: Why should 'from <module> import *' be prohibited?
(6 answers)
Closed 5 months ago.
From the documentation:
The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError.
Why? What's the sense of avoiding to use it in a function? What's the problem?
The CPython implementation uses a special optimisation for local variables: They aren't dynamically looked up at runtime from a dictionary, as globals are, but rather are assigned indices statically at compile time, and are looked up by index at runtime, which is a lot faster. This requires the Python compiler to be able to identify all local names at compile time, which is impossible if you have a wildcard import at function level.
In Python 2, there was still a fallback mechanism that got invoked in cases where it wasn't always possible to determine all local names statically. This mechanism used a dynamic dictionary for local variables, significantly slowing down execution.
For example this code
def f():
exec "x = 2"
print x
works as expected in Python 2, whereas
def f():
exec("x = 2")
print(x)
results in a NameError in Python 3.

from ... import * with __import__ function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
from . import x using __import__?
How does one do the equivalent of import * from module with Python's __import__ function?
How would I do the from ... import * with the __import__ function?
The reason being that i only know the name of the file at runtime and it only has 1 class inside that file.
In case someone reading this wants an actual answer to the question in the title, you can do it by manipulating the vars() dictionary. Yes, it is dumb to do this in most scenarios, but I can think of use cases where it would actually be really useful/cool (e.g. maybe you want a static module name, but want the contents of the module to come from somewhere else that's defined at runtime. Similar to and, IMO, better than the behavior of django.conf.settings if you're familiar with it)
module_name = "foo"
for key, val in vars(__import__(module_name)).iteritems():
if key.startswith('__') and key.endswith('__'):
continue
vars()[key] = val
This imports every non-system variable in the module foo.py into the current namespace.
Use sparingly :)
Don't. Just don't. Do I need to explain just how horrible that it? Dynamically importing (though sometimes inevitable) and importing into global namespace (always avoidable, but sometimes the easier solution and fine withtrusted modules) are bad enough themselves. Dynamically importing into global namespace is... a nightmare (and avoidable).
Just do _temp = __import__(name, globals(), locals(), [name_of_class]); your_class = _temp.name_of_class. According to the docs, this is about what from name import name_of_class would do.

Categories