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
Related
This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 5 years ago.
I can't figure out what I'm doing wrong. It seems I'm not able to use dir() as the default argument to a function's input
def print_all_vars(arg=dir()):
for i in arg:
print(i)
foo=1
If I use
print_all_vars()
gives the output
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
__spec__
but
print_all_vars(dir())
outputs
__builtins__
foo
print_all_vars
So - first, what is going on -
The line containing the def statement is run only once, when the module containing the function is first imported (or on the interactive prompt) - anyway, any expressions used as default parameter values are evaluated a single time, and their resulting object is kept as the default value for that parameter.
So, your dir() call is executed, and the resulting list - a dir on the namespace of the module containing your example function is saved. (The most common related error for Python beginners is to try to put an empty list or dictionary ( [] or {}) as a paramter default: the same list or dictionary will be reused for the lifetime of the function).
That explains why you see in the output some values that won't show up if you call it with a dir from the interactive prompt, like __package__ or __spec__.
Now, your real question is:
... I am actually trying to create an analog of MATLAB's save function
that saves all existing variables to an external file that can be
recalled later –
So, even if your dir() would be lazily executed, when the function is called only, that would still fail: it would still retrieve the variable names from the module where the function is defined, not on the callers.
The coding pattern for doing that would be:
def print_all_vars(arg=None):
if arg is None:
arg = dir()
...
(And this is the most common way to enforce empty lists of dictionaries as default parameters on the function body)
But even this, or if you pass your own list of variable names explicitly to the function, you will still have just a list of strings - not Python objects that need you will want to save.
And - if you want to retrieve the variables from the caller by default, you have a problem in common with having this list of strings: you need to be able to access the namespace of the caller code, in order to either retrieve the variable names existing there, and later to retrieve their contents in order to be saved.
The way to know "who've called your function" in Python is an advanced thing, and I am not even sure it is guarantee to work across all Python implementations - but it will certainly work on the most common (cPython, Pypy, Jython) and even some considered smaller ones (such as Brython):
You call sys._getframe() to retrieve the frame object of the code currently being executed (that is the code in your function itself) - and this frame object will have a f_back attribute, which points to the frame object of the code which called your function. The frame object, on its side, has reference to the globals and locals variables of the code being run as plain dictionaries as f_globals and f_locals respectively.
You can them "save" and "restore" as you want the contents of the global variables on the caller code - but you can't update - using pure Python code - the local variables.
So, just to list by default the global variables on the caller code - you can do:
import sys
def print_all_vars(arg=None):
if arg is None:
arg = list(sys.get_frame.f_back.f_globals.keys())
print (arg)
Being able to properly saving and restoring those variables is another question - as you can see in the comments, you can use pickle to serialize a lot of Python objects - but the caller namespace will have module names (such as mathnp`, etc...) which can't be ordinarily pickled - so you will have to come with an strategy to detect, annotate the used modules, and restoring them, by using further introspection on all objects retrieved.
Anyway, experimenting with the information here should put you on the track for what you want.
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.
Could someone please explain how this little piece of code works?
info = {}
info.update(locals())
info.pop('self', None)
info.pop('info', None)
I am assuming, and please correct me if I am wrong, but it gets all the variables in the current function and puts them in the dict and removes self and the dict it got put in, correct? Is there anything other than self and the dict I might not want going into there?
Would there be anything wrong with just JSON serializing that dict and posting it?
This probably comes from the Django template and the locals trick. The idea is to populate a number of variables inside a function, and use locals() to pass them on to a template. It saves the effort of creating a new dictionary with all those variables.
Specifically, your code creates a dictionary of all the local variables and removes self (the class object parameter) and info (the variable that was just created). All other local variables are returned.
You could then JSON serialize the data, as long as the data can be serialized. DateTime variables must be converted to a string first, for example.
The code creates a new dictionary called 'info' and assigns all of your local python variables to it. NOTE: These are pointers to the same objects in your local environment, so that if you modify a list or dictionary in info it will be changed in your environment as well (this may or may not be the desired behavior).
locals()
Update and return a dictionary representing the current local
symbol table. Free variables are returned by locals() when it is
called in function blocks, but not in class blocks.
Note The contents of this dictionary should not be modified; changes
may not affect the values of local and free variables used by the
interpreter.
info.pop('self', None) and info.pop('info', None) will remove 'self' and 'info', respectively, from your new info dictionary. If they are not present, they return None. Note that info.pop('self') would return a KeyError if 'self' was not in the dictionary.
I have the following django model:
class SomeProfile(models.Model):
type = models.CharField(max_length=1)
Is using "type" as an attribute name considered a bad practice?
Here the attribute is not shadowing "type", so it's not the same question as this one
There's nothing wrong with it. It's not a member of python's reserved keywords.
However, naming a method type() would probably be confusing...
General rule is: don't use names that are taken (e.g. type, file, int, etc.) regardless of whether they're in a "reserved" keywords list or not (since python allows it, it's not really "reserved"). This is mainly important to avoid getting into trouble when you actually need to use the real object (without noticing that you overrode it locally).
If you really want to use one of those names, just append _ at the end (e.g. type_).
In your case, since you're specifying type as a class attribute, it should be considered safe since it can only be accessed through its class (self.type or SomeProfile.type).
Yes - its bad practice. type is very general word from keyword perspective though not a reserved keyword. Even though its not giving any problems currently in your application but it might give in future as it could have been used in some already existing libraries or python extensions.
Example: type being used as a function to get TypeCast information of variable
name = "John"
age = 12
print type(name)
## Above line will return "<type 'str'>"
print type(age)
## Above line will return "<type 'int'>"
Usage of type being used as an attribute is a bad practice.
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.