Very often when I deal with input/output that are generated from different languages, I often have to deal with the null values when I get those input/output into Python. As we all know None is the keyword for Python instead of null, so it often creates error when, say, the null value is in a list. Some libraries already deal with this situation, but some don't. I'm just wondering if it's a good practice to simply set
null = None
Honestly I haven't seen this done before, but I don't know if I'm just not paying attention. Is there any bad side effect for this? Is this even recommended?
EDIT: The current piece I'm working on does contain eval. I didn't it was such an evil thing lol. Someone wrote this a long time ago. I don't know how eval gave impression back then. nonetheless, I think it's a better idea to change the eval part.
Essentially the part that creates problem is when the code tries to eval a list that has null in it.
To be exact, the input here is a list of list that's wrapped in a string.
EDIT2: don't just downvote. I'm simply asking a question
This is not a good idea. It indicates some fuzziness in your program, a blurring of the line between code and input.
Any code you write should use None, not a variable set to None. Having a null constant wouldn't help because you could simply write None.
If you're getting input from the user or from another program, that input would be text. It'd be stored in a string variable as "null". It wouldn't be a raw identifier null. It would be a very poor design if user input could somehow refer to variables in your source code. That would be leaking implementation details.
If you find yourself using eval or equivalent, go directly to jail, do not pass GO, do not collect $200.
You're losing the advantages of None. Try this:
None = "Hello"
It doesn't work (SyntaxError) because assignment to None is prohibited. Creating an extra variable, null, introduces the possibility that null is not None at some future point in your program.
Just use None. None is guaranteed.
I'm imagining you could receive input as a string 'null'. However, this would be a string and not a key word. You'd be free to parse and deal with it as you saw fit. The only way I can imagine using null = None would do anything is if you were trying to evaluate strings as python code like
null = None
`eval('null')`
I'd consider this bad and sloppy coding practice.
I'm working with a response as a dictionary from a GET request from an API and received null and true as values of the dictionary. I took your null = None and it fixed my issue
I also set true = True
return {"cancel_url": null, "initiator_id": null, "initiator_type": null, "is_visible_to_user": true}
NameError: name 'null' is not defined
Related
I am seeing a strange issue using flatbuffers on python. I am trying to store a variable value which is integer, however, when I generate the JSON from the resulting .bin file the key / integer value will not be there.
However, if I simply pass an integer it works fine?
Do I need to do some kind of cast or generate an integer type in the same way as I do for strings?
Here is an example of the code I am running:
varInt = 1
SomeClass.SomeClassStart(my_builder)
SomeClass.SomeClassAddMyValue(my_builder, varInt)
SomeClass.SomeClassAddMyOtherValue(my_builder, 2)
some_class_buffer = SomeClass.SomeClassEnd(my_builder)
which produces json of :
some_class:{
my_other_value: 2
}
I don't understand why one way would work and one wouldn't? I don't have much experience with python and flatbuffers are completely new to me so not sure if theres some nuance that I'm unaware of?
Any help is appreciated.
I found the issue with this. It turns out that I had to set the builder to have the forceDefaults variable set to true.
my_builder.forceDefaults = True
just started learning python. trying to change a columns data type from object to float to take out the mean. I have tried to change [] to () and even the "". I dont know whether it makes a difference or not. Please help me figure out what the issue is. thanks!!
My code:
df["normalized-losses"]=df["normalized-losses"].astype(float)
error which i see: attached as imageenter image description here
Use:
df['normalized-losses'] = df['normalized-losses'][~(df['normalized-losses'] == '?' )].astype(float)
Using df.normalized-losses leads to interpreter evaluating df.normalized which doesn't exist. The statement you have written executes (df.normalized) - (losses.astype(float)).There appears to be a question mark in your data which can't be converted to float.The above statement converts to float only those rows which don't contain a question mark and drops the rest.If you don't want to drop the columns you can replace them with 0 using:
df['normalized-losses'] = df['normalized-losses'].replace('?', 0.0)
df['normalized-losses'] = df['normalized-losses'].astype(float)
Welcome to Stack Overflow, and good luck on your Python journey! An important part of coding is learning how to interpret error messages. In this case, the traceback is quite helpful - it is telling you that you cannot call normalized after df, since a dataframe does not have a method of this name.
Of course you weren't trying to call something called normalized, but rather the normalized-losses column. The way to do this is as you already did once - df["normalized-losses"].
As to your main problem - if even one of your values can't be converted to a float, the columnwide operation will fail. This is very common. You need to first eliminate all of the non-numerical items in the column, one way to find them is with df[~df['normalized_losses'].str.isnumeric()].
The "df.normalized-losses" does not signify anything to python in this case. you can replace it with df["normalized-losses"]. Usually, if you try
df["normalized-losses"]=df["normalized-losses"].astype(float)
This should work. What this does is, it takes normalized-losses column from dataframe, converts it to float, and reassigns it to normalized column in the same dataframe. But sometimes it might need some data processing before you try the above statement.
You can't use - in an attribute or variable name. Perhaps you mean normalized_losses?
I am using a SortedSet from the sortedcontainers library. The set contains Match objects which define a start attribute which is used to sort:
class Match:
def __lt__(self, other):
return self.start < other.start
Matches are constantly added (SortedSet.add) and discarded (SortedSet.discard) from the set.
Matches may have the same start. Matches may see their start changed while existing in the set.
Everything seems to work without any issues until I get the following error when trying to discard a match sortedset.discard(match):
ValueError: <Match: X vs Y> not in list
The match is present in the set, as match in sortedset returns True. Not that it should matter since discard removes quietly.
I have absolutely no idea why this is happening and I have been trying to figure out a solution for a couple of days, no success yet. I would provide more information if I had any clue of what may be wrong, but I am just clueless. Please ask any information you need and I will deliver.
Matches may have the same start. Matches may see their start changed while existing in the set.
This violates the constraints that containers use to track their elements.
You can't change the sort order of an element while it is in a container. The container has no way of knowing that the sort order has changed.
Objects must be different.
If you read the documentation for sortedset, it clearly states:
The hash and total ordering of values must not change while they are stored in the sorted set.
There doesn't even exist a total ordering for your elements, because there exist x != y where it is neither true that x < y or x > y.
You haven't mentioned __hash__ at all.
I am not sure how you would expect to solve these problems, since I am not familiar with your code, and solving them may require some redesign work. However, these problems are what is causing the unexpected behavior in your program.
can someone help me with this?
pts.InsertPoint(fl[i+1][j+1][k+1], xx[0][i+1], yy[0][j+1], zz[0][k+1])
TypeError: InsertPoint argument 1: integer argument expected, got float
fl is supposed to have float, I have the array from real world experiment, I can't change the values to int.
Is this an issue related to InsertPoint, is it only taking int? Can someone help me fix it?
Also, I don't have experience in Python, never wrote a program, this is the first program I am working with, I made changes to an old program to get it work for my purposes, but can't figure out what I did wrong
Thanks :)
If you look at the documentation of vtkpoints::InsertPoint you will see that the expected arguments are (id,x,y,z). You use this method when you have to want to set the value of the point at position id (that's why it must be an integer). http://www.vtk.org/doc/nightly/html/classvtkPoints.html#ab7f990c73fb291737abe4203994ce2a2
from the python shell, you can also check help(pts.InsertPoint) - but since these are wrapped objects sometimes the help appears a bit obscure.
The method InsertNextPoint, instead, just requires x,y,z and can be used as you are doing. It doesn't require an explicit id because it will just your point at the end
Specifically for python , you could be interested also in vtk.util.numpy_support which makes conversions between numpy and vtk elements easier (you can convert your points from numpy to a vtkdoublearray, then assign it to a vtkpoints with the method setdata )
The problem is not whether or not fl is composed of floats. The problem is that the method signature for InsertPoint expects each value to be an int.
From the python documentation:
exception TypeError:
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
This information is clearly available in the error message you pasted - it has both the exception type (TypeError) and the object by which it was thrown (InsertPoint). Had you accidentally included a float in your array indexers, the exception would have been thrown by something other than InsertPoint.
In the future, you should do some research on Google based on your exception error. I'm not telling you anything you couldn't find there.
If you still want to use InsertPoints, you have two options:
You can use the (int) cast to truncate edit: the first of your arguments to the whole, integer value (1.2 truncates to 1, 2.67 to 2, etc.), like so:
int(fl[i+1][j+1][k+1])
You can do #1, but round the value to the nearest integer value, like below (keep in mind that you'll need to import Math):
int(Math.Round(fl[i+1][j+1][k+1]))
Try wrapping each or your values in int(), like so:
pts.InsertPoint(int(fl[i+1][j+1][k+1]), int(xx[0][i+1]), int(yy[0][j+1]), int(zz[0][k+1]))
I am writing a python extension to provide access to Solaris kstat data ( in the same spirit as the shipping perl library Sun::Solaris::Kstat ) and I have a question about conditionally returning a list or a single object. The python use case would look something like:
cpu_stats = cKstats.lookup(module='cpu_stat')
cpu_stat0 = cKstats.lookup('cpu_stat',0,'cpu_stat0')
As it's currently implemented, lookup() returns a list of all kstat objects which match. The first case would result in a list of objects ( as many as there are CPUs ) and the second call specifies a single kstat completely and would return a list containing one kstat.
My question is it poor form to return a single object when there is only one match, and a list when there are many?
Thank you for the thoughtful answer! My python-fu is weak but growing stronger due to folks like you.
"My question is it poor form to return a single object when there is only one match, and a list when there are many?"
It's poor form to return inconsistent types.
Return a consistent type: List of kstat.
Most Pythonistas don't like using type(result) to determine if it's a kstat or a list of kstats.
We'd rather check the length of the list in a simple, consistent way.
Also, if the length depends on a piece of system information, perhaps an API method could provide this metadata.
Look at DB-API PEP for advice and ideas on how to handle query-like things.