How to import a module's variable in python? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I want to import a module named "config" and I want import config.times. But in my code, times is a element in a list name_list, it means:
name_list = ['times','date','hours'].
When I want to use config.times ,I try config.name_list[0]. Of course there is an error " 'module' object has no attribute 'name_list'". So how can I fix it? Thanks.
---More details:
My code is: config.py,main.py .In config.py, times = ['00:00:00','12:00:00'],and in main.py ,name_list = ['times','date','hours'],I want exec now = config.times in main.py.

If I understand correctly, you want to access the times variable from a module you've imported, but you want that name (times) to come from another variable, rather than being hard coded.
That's possible to do in a few ways. The easiest is probably to use the getattr function to get the attribute from the module object:
import config
name = "times" # or wherever, e.g. name_list[0]
results = getattr(config, name) # will get a reference to config.times
I'm not sure doing this is really a great idea though. Generally speaking, variable names (such as times in the config module) should be intended for programmers to interpret. They should not be data. If you want to look up data by name, you should generally use a dictionary to store the keys and values, rather than using the namespace of a module.
So for instance, your config module could have a dictionary named data, and you could move your current times value to data['times']. Then looking up a value by name is just a dictionary lookup: config.data[name].

Try using following in main.py :
from config import times
or
name_list = ['config.times','date','hours']
EDITED from here on for more clarification
and then use :
eval(name_list[0]) # for evaluating config.times
I hope this is more clear
please remove the downvote.

Related

module as no attribute - self.variable.function(self) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a module call pcb_files.py that only have some imports like this -> import read
Then I have another module call Easy.py, that have a class (Mainwindow) and a method/funtion (function_pcb1)
Class MainWindow(xxx,xxx)
.....
.....
def func_pcb1(self):
pcb_files.read.main(self)
Right now everytime I press a pushbutton in my app I run the funtion "main" that is inside "read". So far so good
What I want:
def func_pcb1(self):
script=self.nome_do_script
pcb_files.script.main(self)
Like you see in, now I have this : script=self.nome_do_script where "script" is a string type.
And now I just want to change one thing, in the place of "read" I want to put the "script" like i do in the image but it gives me an error -> AttributeError: module 'pcb_files' has no attribute 'script'
Resuming, instead of call whats inside "script" variable, it's calling the name script itself.
Now you're asking why do you want that ? -> Answer: I want to call, and show to the user, in my app different files that will do different things
something.other is what Python calls attribute access, where "other" is the attribute name. If you want to access an attribute with a dynamic name, you can use getattr.
def func_pcb1(self):
script = self.nome_do_script
getattr(pcb_files, script).main(self)
In the long term, you'll want to learn how to use dictionaries for these kinds of things.

python see the full definition from the name of the function [duplicate]

This question already has answers here:
How can I get the source code of a Python function?
(13 answers)
Closed 4 years ago.
I recently asked a question with title "python find the type of a function" and got very helpful answers. Here is a related question.
Suppose I import *.py files written by me, and these imports result in f being one of the functions defined by me. Now I write to my python interpreter x = f. Later, I want to see the full definition of f, preferably with comments still in place, knowing only x. Is this possible? Does python remember which file the definition was imported from, which is, of course, not enough to give the full definition of f, unless one can find the actual relevant definition?
The built in help(object) will give you the correct documentation if you alias k to some function you commented - same for inspect.getsource(k) - they know which function is ment by your variable name alias k at this time.
See:
the help() built in
inspect.getsource(k)
(taken from here)
Example:
# reusing this code - created it for some other question today
class well_documented_example_class(object):
"""Totally well documented class"""
def parse(self, message):
"""This method does coool things with your 'message'
'message' : a string with text in it to be parsed"""
self.data = [x.strip() for x in message.split(' ')]
return self.data
# alias for `parse()`:
k = well_documented_example_class.parse
help(k)
Prints:
Help on function parse in module __main__:
parse(self, message)
This method does coool things with your 'message'
'message' : a string with text in it to be parsed
Same goes for inspect.getsource(k):
# from https://stackoverflow.com/a/52333691/7505395
import inspect
print(inspect.getsource(k))
prints:
def parse(self, message):
"""This method does coool things with your 'message'
'message' : a string with text in it to be parsed"""
self.data = [x.strip() for x in message.split(' ')]
return self.data
You should think of the way Python uses variables. You have objects (can be classes, functions, lists, scalars or whatelse) and variables that only hold references to those objects.
That explains why when multiple variables point to the same mutable object, if you change it through one of those variables, the change in visible in all other ones.
This is the same thing here. The function object manages all its attributes: its docstring, its code, and its source (if it has: C function show no source). Assigning the function to a new variable does not hide the object behind anything: you still access the original object.
Things would go differently with decorators, because the decorator creates a new object, and the original object is only available to the decorated one.

Delete Python Object without deleting all references first [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Easy question, is it possible to remove an object from memory and setting all remaining pointers to it to undefined?
You cannot explicitly free memory in Python.
If you want to call del x without having other references to x preventing it from getting garbage collected, you may want to check out weakrefs.
In case you are looking to create some sort of 'cancelable' object that can be invalidated and cause all subsequent attempts to use it to get either a None value or an error, you can do that (after a fashion), but your code will have to be disciplined not to get a direct reference ever, but always refer to the object in a special way, for example:
class deletable(object):
def __init__(self, value):
self.v = value
def destroy(self):
if hasattr(self,"v"): delattr(self, "v")
# create instance
x = deletable( { "key" : "value", "other" : 13 } )
# access
print (x.v["key"])
# re-assign
x.v = { "another" : "dict" }
# "destroy" - option 1 - trigger error on use
x.destroy()
# "destroy" - option 2 - make it None (free memory, but keep x.v valid)
x.v = None # or x.v = {}, if you want to keep it with the original data type of dict()
Now, this "works" on the condition that you never (EVER) do z = x.v and always pass around x as a whole.
(If you know in advance the data type and it is always the same, e.g., dict, you can do a bit better and have the custom object respond to things like x["key"], x.update(some_dict), etc., i.e., look like a regular dict, but still able to call x.destroy() and make it fail further attempts to access. Advanced stuff, I won't write a whole article here on this, not even knowing that I made a correct guess as to what you really need).

Changing variables in separate Python files

So I just found out today that I can import variables from other Python files. For example, I can have a variable green = 1, and have a completely separate file use that variable. I've found that this is really helpful for functions.
So, here's my question. I'm sorry if the title didn't help very much, I wasn't entirely sure what this would be called.
I want my program to ask the player what his or her name is. Once the player has answered, I want that variable to be stored in a separate Python file, "player_variables.py", so every time I want to say the player's name, instead of having to go to from game import name, I can use from player_variables import name, just to make it easier.
I fully understand that this is a lazy man's question, but I'm just trying to learn as much as I could. I'm still very new, and I'm sorry if this question is ridiculous. :).
Thanks for the help, I appreciate it. (be nice to me!)
From your question, I think you're confusing some ideas about variables and the values of variables.
1) Simply creating a python file with variable names allows you to access the values of those variables defined therein. Example:
# myvariables.py
name = 'Steve'
# main.py
import myvariables
print myvariables.name
Since this requires that the variables themselves be defined as global, this solution is not ideal. See this link for more: https://docs.python.org/2/reference/simple_stmts.html#global
2) However, as your question states that you want your program to save the variable of some user-entered value in the python file, that is another thing entirely as that's metaprogramming in python - as your program is outputting Python code, in this case a file with the same name as your variables python file.
From the above, if this is the means by which you're accessing and updating variables values, it is a simpler idea to have a config file which can be loaded or changed at whim. Metaprogramming is only necessary when you need it.
I think you should use a data format for storing data, not a data manipulating programming language for this:
import json
import myconfig
def load_data():
with open(myconfig.config_loc, 'r') as json_data:
return json.loads(json_data.read())
def save_data(name, value):
existing_data = load_data()
existing_data[name] = value
with open(myconfig.config_loc, 'w') as w:
w.write(json.dumps(existing_data, indent=4, sort_keys=True))
You should only store the location of this json file in your myvariables.py file, but I'd call it something else (in this case, myconfig, or just config).
More on the json library can be found here.

Programming practice: dependency of one function on another [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am trying to improve my program so that it conforms to good programming
practices. So I am looking for suggestions on whether the way I have programmed
something is a good way of doing it.
I have a module called dbfunctions.py in which I have defined:
dbparams = {
'dbname': 'qualitysimparams',
'tablename': 'qualityparams',
'tablecols': ('numpeople', 'numreviews', 'prophunters',
'utility_funcform', 'goods'
)
and a function:
def obtainid_ifrecord(dbname, tablename, tablecols, values):
'''Checks if there already exists a record with given <values>.
If so, returns the id of that record, otherwise returns zero.'''
con, c = connecttodb()
q1 = "use {0}".format(dbname)
c.execute(q1)
q2p1 = "select id from {0} ".format(tablename)
q2p2 = "where " + " = %s and ".join(tablecols) + " = %s"
q2 = q2p1 + q2p2
c.execute(q2, values)
res = c.fetchall()
c.close()
con.close()
if res:
return res[-1][0]
else:
return 0
There are other functions and variables in addition to the above two, but
they are not relevant for this post.
In another file I have a function:
def checkif_paramcomboexists(numpeople, numreviews, prophunters,
utility_funcform, goods):
'''Check in the database if the simulation has been run with the
specified parameters. If so return the id of that run.
'''
goodsjson = sjson.dumps(goods)
# paramvalues: in same order as listed in dbf.dbparams['tablecols']
paramvalues = (numpeople, numreviews, prophunters,
utility_funcform, goodsjson)
id = dbf.obtainid_ifrecord(dbf.dbparams['dbname'],
dbf.dbparams['tablename'],
dbf.dbparams['tablecols'],
paramvalues)
return id
It seems to me that the fact that hardcoding the variable names in the
paramvalues variable in function checkif_paramcomboexists is not a good practice.
If later I change the order of variables in dbfunctions.dbparams['tablecols'] for any
reason, checkif_paramcomboexists function will fail (and can fail silently depending
on the data types). One way to get around this is to define:
paramvalues = [eval(x) for x in dbf.dbparams['tablecols']]
But I have heard that generally it is a bad practice to use eval (although I do not know
why and when it is okay to use it). My questions are:
(i) Is it okay the way I have coded this in regards to the concern I have? I think the answer
is 'No', but just want to check with the experts here.
(ii) Is use of eval as I have indicated an acceptable solution?
(iii) If answer to (ii) is 'no', what is the alternative?
Thank you for reading through this.
You're right about the hardcoding not being great, and definitely stay away from eval. If you don't want to use *args or **kwargs (which are really better options, by the way), you can use the inspect module to do what you're trying to do.
import inspect, collections
def checkif_paramcomboexists(numpeople, numreviews, prophunters,
utility_funcform, goods):
...
temp = inspect.getargvalues(inspect.currentframe())
args = temp[0]
valuedict = temp[-1]
ordered_args_dict = collections.OrderedDict(sorted(valuedict.items(), key=lambda x: args.index(x[0])))
paramvalues = ordered_args_dict.values()
...
Basically, what's going on here is that inspect.getargvalues(inspect.currentframe()) gets you an object where the first item is a properly ordered list of the argument names and the last item is a dictionary of the argument names and values. We then create an ordered dictionary by grabbing the argument name/value mapping from the dictionary, and ordering it based on the list order.
What you end up with is an OrderedDict that has all of the arguments with their values, but also has them in the right order. That way, you can still choose to refer to them by name (e.g., ordered_args_dict['numpeople']), but if you can still get all the values in order as you wanted with ordered_args_dict.values(), which will give you the output you're looking for for paramvalues: a properly ordered list of the arguments, no matter what the name is.
This situation really calls for an object. You are duplicating what is essentially instance information about a specific database table in 2 places, so it would make sense to make both these functions in to methods of some sort of database table interface object that has a tablecols attribute, then use self.tablecols in both methods.

Categories

Resources