python, how to tell what type of obj was returned

How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)


Asked by: Chelsea429 | Posted: 06-12-2021






Answer 1

Use isinstance(item, type) -- for instance:

if isinstance(foo, int):
    pass # handle this case

However, explicit type checking is not considered a good practice in the Python world -- it means that much of the power of duck typing is lost: Something which walks and quacks like a duck should be allowed to be a duck, even if it isn't! :)

Answered by: Edgar522 | Posted: 07-01-2022



Answer 2

Use the built-in "type" function, e.g. type(10) -> .

Answered by: Steven793 | Posted: 07-01-2022



Similar questions

python - I want the actual file name that is returned by a PHP script

I am writing a python script that downloads a file given by a URL. Unfortuneatly the URL is in the form of a PHP script i.e. www.website.com/generatefilename.php?file=5233 If you visit the link in a browser, you are prompted to download the actual file and extension. I need to send this link to the downloader, but I can't send the downloader the PHP link. How would I get the full file name in a usable varia...


python - What's an easy and fast way to put returned XML data into a dict?

I'm trying to take the data returned from: http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true Into a dict in a fast and easy way. What's the best way to do this? Thanks.


python - None value returned

The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None"


python - Use 1 out of 2 returned values as string

divmod(X, Y) returns (A, B) How would I turn either A or B into a string? EDIT: to clarify, I'd like to use them 1 at a time :)


python - Cannot append to a returned list?

def f(): lst = ['a', 'b', 'c'] return lst[1:] why is f().append('a') is None == True even though f().__class__ is <type 'list'> and f() == ['b', 'c']


python - Handle JSON Decode Error when nothing returned

I am parsing json data. I don't have an issue with parsing and I am using simplejson module. But some api requests returns empty value. Here is my example: { "all" : { "count" : 0, "questions" : [ ] } } This is the segment of my code where I parse the json object: qByUser = byUsrUrlObj.read() qUserData = json.loads(qByUser).decode('utf-8') ...


python - celery tasks with returned data: doing it wrong or doing it right?

I'm learning to use celery. I have a function (in a Flask application) in somewhat pseudocode from what I've learned so far: def do_a_task_route(): try: result = a_celery_task.apply_async(args=[request_data]) returned = a_celery_task.AsyncResult(result.task_id).get(timeout = 2.0) return jsonify(response = returned['response']) except: return jsonify(response = "some ...


python - Use pylab to plot image returned from Scipy

I'm working to migrate from MatLab to python in Sage. So I use these commands and I faced this error in Sage: from scipy import misc l = misc.lena(); import pylab as pl pl.imshow(l) The Error or message (i don't know) is: matplotlib.image.AxesImage object at 0xb80198c And it doesn't show any image


Python JSON How to filter returned data

I am fetching data using the Discogs API and I wanted to restrict the JSON to only records that have format as 'CD' or 'Album' or 'Maxi-Single'. I am not sure how to filter fetched data since Discogs doesnt not have a easier way to filter this from the initial request itself. You'll notice that the JSON URL mentioned below has 'DVD' and 'VHS' that I would like to omit. Any idea/clues how I can filter this after fetching is...


python - Choose list which is returned by def

I have a definition to separate some coordinates on specific properties. For this separation I use 1 definition and within the definition i have 9 lists (different criteria's). Now for the output i just want the list defined by me. Otherwise I cannot use it for plotting. def sorteerCord(cord): tweestijging=[] stijginggelijk=[] stijgingdaling=[] tweedaling=[] dalinggelijk=[] dalingst...


How do you address data returned to a socket in python?

Say you are telneting into IRC to figure out how it all works. As you issue commands the IRC server returns data telling you what it's doing. Once I have created a default script that basically is how a normal IRC connection between server and client occurs, if it ever deviates from that it won't tell me what is wrong. I need to be able to throw exceptions based on what the server returns to me. How do I do that in pyt...


Can not remove french letters in a string returned by Python glob

I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The supprime_accent seems to work ok. However, it doesn't rename files returned by the glob function. Does anybody knows what can be the reason? Is it related with glob encoding? def supprime_accent(ligne): """ supprime les ac...


python - I want the actual file name that is returned by a PHP script

I am writing a python script that downloads a file given by a URL. Unfortuneatly the URL is in the form of a PHP script i.e. www.website.com/generatefilename.php?file=5233 If you visit the link in a browser, you are prompted to download the actual file and extension. I need to send this link to the downloader, but I can't send the downloader the PHP link. How would I get the full file name in a usable varia...


python - What's an easy and fast way to put returned XML data into a dict?

I'm trying to take the data returned from: http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true Into a dict in a fast and easy way. What's the best way to do this? Thanks.


python - None value returned

The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None"


python - Any reason there are no returned value from set.add


python - Loading haar cascade file in OpenCV -> "OpenCV returned NULL"

OpenCV 2.1 with Python 2.6 bindings: >>> cv.Load('~/Desktop/data/haarcascades/haarcascade_eye.xml') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: OpenCV returned NULL Any explanations for this? This happens on OS X and Ubuntu. The same error is given for every file. It worked in (I think) 2.0. Edit- I guess it only breaks s...


PLPGSQL returned array, how to parse in Python?

I'm getting an array from plpgsql that looks like this: [0:2]={ "(ab023500-ceef-41d6-af33-635964dbffde,Koen,\"\",Schmeets,{koen@heizoo.com},31631205427},\"{\"\"Test categorie\"\"}\",{ff0000})", "(384cb1e9-58b9-4bdf-9da6-eb3d9355471b,Marc,\"\",Vrijhof,{},{},\"{\"\"Test categorie\"\"}\",{ff0000})", "(9c19ec...


python - Use 1 out of 2 returned values as string

divmod(X, Y) returns (A, B) How would I turn either A or B into a string? EDIT: to clarify, I'd like to use them 1 at a time :)


how to count value returned from select query in python

I want to count the total number of rows returned by query. I am able to retrieved rows returned by query but what if i need to work in case when no data exits. that is when query returns no va from database. the code i used to solve this problem is : try: cur.execute(query) id = cur.fetchone()[0] if(id is None): return '-1' else: return id ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top