Reputation: 41
I have a function that returns two different types (bool
and int
):
def limit_reached():
rate_limit = api.GetRateLimitStatus()
if not rate_limit['remaining_hits'] == 0:
return False
else:
return rate_limit['remaining_hits']
Basically, I want to be able to call the function to see if the "limit" limit has been reached. If it has not, before continuing, print how many 'remaining_hits'
are left.
So far I have this, but can't figure out how to efficiently show 'remaining_hits'
without calling the GetRateLimitStatus()
function again:
if limit_reached():
print "Limit reached. Exiting"
exit()
else:
##Print remaining hits
##Continue...
Also, if it helps, I am using the Twitter API for Python
Upvotes: 0
Views: 2864
Reputation: 77464
Store the result in a variable?
remaining = limit_reached()
if not remaining:
print "Limit reached."
else:
print "Remaining:", remaining
P.S. you can also return 0
when the limit was reached... No need to return False
when it actually means 0
.
Upvotes: 3
Reputation: 9665
As a commenter pointed out, returning different variable types is bad style. It is fairly easy to always return a boolean value, like so:
def limit_reached():
rate_limit = api.GetRateLimitStatus()
return rate_limit['remaining_hits'] == 0
rate_limit['remaining_hits'] == 0
is a complete statement that will return a 'true' or 'false' value, the result of which you can return from your function. Note that you do need to use two equals signs.
If you need the integer value itself, you can always return that instead, and test the condition in your other code, like so:
def limit_reached():
rate_limit = api.GetRateLimitStatus()
return rate_limit['remaining_hits']
if limit_reached() == 0:
print "Limit reached. Exiting"
exit()
else:
##Print remaining hits
##Continue...
Or, you could take advantage of the fact that all numbers (integer, float, double, it doesn't matter) with an exact value of 0
are treated as false
(other constants treated as false
include []
, ()
, ''
, or '{}' - see here).
if limit_reached():
##Print remaining hits
##Continue...
else:
print "Limit reached. Exiting"
exit()
Note that the clauses have been reversed in this case.
Upvotes: 1
Reputation: 29710
You should redefine your limit_reached function:
def limit_reached():
return api.GetRateLimitStatus()['remaining_hits']
then something like:
remaining = limit_reached()
if remaining: # or 'remaining > 0' if you want to be explicit
##Print remaining hits
##Continue...
else:
print "Limit reached. Exiting"
exit()
Upvotes: 1
Reputation: 27605
In python, the integer '0' is identically equivalent to 'False'. So, for any and every truth test in Python, the integer '0' evaluates to false.
For what I see, you can adapt your code to use this fact.
Hope it helps.
Upvotes: 4