assign a attribute using getattr - python

I try to assign value to attributes of some calss
like the following:
for name in dir(modelType):
if request.get(name):
getattr(model, name) = request.get(name)
but get the excption:
"can't assign to function call"
how can I change attributes without knowing them at complie time?

You use setattr() to assign values to attributes.
See: http://docs.python.org/library/functions.html#setattr

setattr(model, name, request.get(name))
but I'd recommend saving request data in a dictionary, dedicated class, or accessing it directly - unless you're doing specific metaprogramming/introspection, setattr is often the wrong tool for the job.

Related

Alter string in void function

I stumbled upon a low-level Python problem that I cannot understand. I want to do something to a string inside a function and keep those alterations.
name = 'name'
def get_new_name(name):
name = 'new_name'
get_new_name(name)
print(name) # expected 'new_name', got 'name'
I would expect that I get new_name printed, however, the result is name.
I know I could get what I want by using return in the function, but can I somehow use a void-like function as described here to get what i want?
You cannot modify immutable objects in python, no. Any reassignment does not modify the original object, but simply changes the reference that the variable points to.
With mutable objects, you can modify it contents, and the changes will be seen when accessing the object via any variables/references that point to it.
Understanding the difference between objects and references is the key to understanding this.
Since you're curious to know if this is possible... it is! But only if you wrap your string inside something else, say, a dict.
def get_new_name(d):
d['name'] = 'new_name'
name = 'name'
d = {'name' : name}
get_new_name(d)
name = d['name']
print(name)
'new_name'
You'd also need to decide on some protocol that you and the function agree upon for smooth communication between each other.
Sure, you could also use a global variable, but your question wasn't really about that... and I wouldn't recommend doing it either - it's bad practice to create impure functions.
Don't pass name to the function, and change the value of the global one. But it's not recommended...
def get_new_name():
global name
name = 'new_name'
your name variable in your void function is only local and does not share the same scope as your global variable name. Once your function finishes running, it discards the local variable with 'new_name' in it. Unless you include the print statement inside the function, which is pretty redundant.
If you want to simply access a global variable you just use its name.
However to change its value you need to use the global keyword.
From https://stackoverflow.com/a/10588342/6225257

How do I specify a dict dtat type in a python 3 parameter

I am trying to pass a dict variable into a function in Python 3 and then trying to iterate through the keys by calling the .keys() function. However I don't know how to specify the type of the parameter.
def DisplayStock(StockDict):
for key in StockDict.keys():
The error I am getting is
for key in StockDict.keys():
AttributeError: 'function' object has no attribute 'keys'
I guess You ask about pep-484
def DisplayStock(StockDict: dict):
for key in StockDict.keys()
StockDict is a parameter name, dict is a parameter type.
It seems like you are just passing something wrong to the function. From the error it seems like you are giving it a function. Maybe you should put () behind the argument that is causing the error.
Normally you don't need to specify a type. The function will take any type.
If you want to check if the passed argument is a dict you could use:
if isinstance(Stockdict, dict):
for key in Stockdict.keys()
This is not very pythonic though. Just don't pass a non dict like object to the function.
The problem is not in the parameter type. Python is happy for just a variable name and as the original code and then use the .keys method. The error was in a different part of the code I missed brackets on a function call and had set my dictionary object to be a function reference.

Python Access object content

I wonder how to access the content of the following object with python:
<Quota: (injected_file_content_bytes, 10240)>
I already tried to access the content of my variable called myQuota with myQuota[0] and myQuota.injected_file_content_bytes. None of them worked.
Try dir(myQuota) to see what attributes the object has. Then take it from there (or edit your question to include it) and consider what you can do with it. Alternatively, there must be some documentation explaining what this object contains.
What does the built-in dir function do?
Without arguments, return the list of names in the current local
scope. With an argument, attempt to return a list of valid attributes
for that object.
You can also use __dict__
myQuota.__dict will give you the object attributes in form of key value pairs

How to verify Class attribute or method exists

I apology ahead if this is a repost.
I'm currently using a following "self-invented" verification method to check if a Class's attribute (or method) exists before trying to access it:
if 'methodName' in dir(myClassInstance): result=myClassInstance.methodName()
I wonder if there is a more common "standardized" way of doing the same.
Use hasattr. It returns True if a given object has a given name as an attribute, else False:
if hasattr(myClassInstance, 'methodName'):
... # Whatever you want to do as a result.
Use hasattr(myClassInstance, 'methodName').
Another possibility is to just try accessing it and handle the exception if it's not there:
try:
myClassInstance.methodName()
except AttributeError:
# do what you need to do if the method isn't there
How you'll want to handle this depends on why you're doing the check, how common it is for the object to not have that attribute, and what you want to do if it's not there.

Trouble with the scope of variables in a class?

So I'm in the process of making a class in Python that creates a network (with pybrain) using solely the numeric input it's given {just a little process to get my feet wet in Pybrain's API}.
My problem is, I'm rather unfamiliar with how scopes work in classes, and while I basically have the program set up properly, it keeps returning a keyerror.
All the variables needed to be acted upon are created in the init function; the method I'm working on for the class is trying to call upon one of the variables, declared in the init function using the vars()[] method in Python. (you can actually see a portion of the code's...rough draft here:
Matching Binary operators in Tuples to Dictionary Items
Anyways, the method is:
def constructnetwork(self):
"""constructs network using gathered data in __init__"""
if self.recurrent:
self.network = pybrain.RecurrentNetwork
#add modules/connections here
elif self.forward:
self.network = pybrain.FeedForwardNetwork
else:
self.network = pybrain.network
print vars()[self.CONNECT+str(1)]
print vars()[self.CONNECT+str(2)]
print self.network
(pardon the bad spacing, it didn't copy and paste over well.) The part that's raising the KeyError is the "print vars()[self.CONNECT+str(1)], which should retreive the value of the variable "Connection1" (self.CONNECT = 'Connection'), but calls a keyerror.
How do I get the variables to transfer over? If you need more information to help just ask, I'm trying to keep the quesiton as short as possible.
vars() returns a reference to the dictionary of local variables. If you used vars() in your __init__ (as the code in the post you linked to suggests), then you just created a local variable in that method, which isn't accessible from anywhere outside that method.
What is it that you think vars() does, and what are you trying to do? I have a hunch that what you want is getattr and setattr, or just a dictionary, and not vars.
Edit: Based on your comment, it sounds like, indeed, you shouldn't use vars. You would be better off, in __init__, doing something like:
self.connections = {}
self.connections[1] = "This is connection 1"
then in your method, do:
self.connections[1]
This is just a vague guess based on your code, though. I can't really tell what you are intending for this "connection". Do you want it to be some data associated with your object?

Categories