why python3 inspect.isawaitable return 256? - python-3.5

as the picture shows. What is the meaning of 256 here and why not return True? Thanks for any help
!

You should treat it as a "truthy" value. It's actually a CPython's implementation detail which you should probably not concern yourself about. Just do:
if inspect.isawaitable(coro):
In case you wonder, here's the implementation of said function from inspect.py:
def isawaitable(object):
"""Return true is object can be passed to an ``await`` expression."""
return (isinstance(object, types.CoroutineType) or
isinstance(object, types.GeneratorType) and
object.gi_code.co_flags & CO_ITERABLE_COROUTINE or
isinstance(object, collections.abc.Awaitable))
The piece responsible for your return value is
object.gi_code.co_flags & CO_ITERABLE_COROUTINE
Which actually evaluates to 256(2^8).

Related

Simplifying Init Method Python

Is there a better way of doing this?
def __init__(self,**kwargs):
self.ServiceNo = kwargs["ServiceNo"]
self.Operator = kwargs["Operator"]
self.NextBus = kwargs["NextBus"]
self.NextBus2 = kwargs["NextBus2"]
self.NextBus3 = kwargs["NextBus3"]
The attributes (ServiceNo,Operator,...) always exist
That depends on what you mean by "simpler".
For example, is what you wrote simpler than what I would write, namely
def __init__(self,ServiceNo, Operator, NextBus, NextBus2, NextBus3):
self.ServiceNo = ServiceNo
self.Operator = Operator
self.NextBus = NextBus
self.NextBus2 = NextBus2
self.NextBus3 = NextBus3
True, I've repeated each attribute name an additional time, but I've made it much clearer which arguments are legal for __init__. The caller is not free to add any additional keyword argument they like, only to see it silently ignored.
Of course, there's a lot of boilerplate here; that's something a dataclass can address:
from dataclasses import dataclass
#dataclass
class Foo:
ServiceNo: int
Operator: str
NextBus: Bus
NextBus2: Bus
NextBus3: Bus
(Adjust the types as necessary.)
Now each attribute is mentioned once, and you get the __init__ method shown above for free.
Better how? You don’t really describe what problem you’re trying to solve.
If it’s error handling, you can use the dictionary .get() method in the event that key doesn’t exist.
If you just want a more succinct way of initializing variables, you could remove the ** and have the dictionary as a variable itself, then use it elsewhere in your code, but that depends on what your other methods are doing.
A hacky solution available since the attributes and the argument names match exactly is to directly copy from the kwargs dict to the instance's dict, then check that you got all the keys you expected, e.g.:
def __init__(self,**kwargs):
vars(self).update(kwargs)
if vars(self).keys() != {"ServiceNo", "Operator", "NextBus", "NextBus2", "NextBus3"}:
raise TypeError(f"{type(self).__name__} missing required arguments")
I don't recommend this; chepner's options are all superior to this sort of hackery, and they're more reliable (for example, this solution fails if you use __slots__ to prevent autovivication of attributes, as the instance won't having a backing dict you can pull with vars).

Using 2 stacks to create a Queue

class Queue2Stacks(object):
def __init__(self):
# Two Stacks
self.instack = []
self.outstack = []
def enqueue(self,element):
# Add an enqueue with the "IN" stack
self.instack.append(element)
def dequeue(self):
if not self.outstack:
while self.instack:
# Add the elements to the outstack to reverse the order when called
self.outstack.append(self.instack.pop())
return self.outstack.pop()
Can someone please help me understand this question? I don't really understand how does the if not self.outstack work here. I thought the self.outstack start with an empty list, why would it triggers this statement? I also don't understand the while self.instack here, self.instack is a list that we appended from enqueue function right? What would break this while loop?
The if condition you refer to:
if not self.outstack:
...means "if outstack is empty". This is necessary, because the intended action is to pop a value from that stack (see return statement). Now if there is nothing there, we cannot just raise an exception "sorry, nothing there any more", as there might still be values in the other stack : instack. So in that case we need to return a value from that stack: the value we need to return is at the bottom of instack. So we will need to pop all values from that stack, and append them to outstack, which effectively will put them in reverse order: the value that was at the bottom of instack, will end up at the top of outstack, and that is exactly what we want, because we will pop that element as return value.
The while condition is saying: "while there are still values in instack". This is needed, because we want all values to be popped from that stack.
Better understanding of the loop structures may help with this piece of code.
Here's a resource: http://openbookproject.net/thinkcs/python/english3e/conditionals.html
if not (apples >= 5):
print("You have a few apples only.")
is similar to that of:
if (apples <= 5):
print("You have a few apples only.")
the logic gate is a little more deeper with the understanding of "not" as in not a "!" operator. Hope that helps with the understanding of your code.

How to return a variable from a python function with a single parameter

I have the following function:
def test(crew):
crew1 = crew_data['CrewEquipType1']
crew2 = crew_data['CrewEquipType2']
crew3 = crew_data['CrewEquipType3']
return
test('crew1')
I would like to be able to use any one of the 3 variables as an argument and return the output accordingly to use as a reference later in my code. FYI, each of the variables above is a Pandas series from a DataFrame.
I can create functions without a parameter, but for reason I can't quite get the concept of how to use parameters effectively such as that above, instead I find myself writing individual functions rather then writing a single one and adding a parameter.
If someone could provide a solution to the above that would be greatly appreciated.
Assumption: You problem seems to be that you want to return the corresponding variable crew1, crew2 or crew3 based on your input to the function test.
Some test cases based on my understanding of your problem
test('crew1') should return crew_data['CrewEquipType1']
test('crew2') should return crew_data['CrewEquipType2']
test('crew3') should return crew_data['CrewEquipType3']
To accomplish this you can implement a function like this
def test(crew):
if crew=='crew1':
return crew_data['CrewEquipType1']
elif crew=='crew2':
return crew_data['CrewEquipType2']
elif crew=='crew3':
return crew_data['CrewEquipType3']
...
... # add as many cases you would like
...
else:
# You could handle incorrect value for `crew` parameter here
Hope this helps!
Drop a comment if not

To find a string from a list is not working as expected using contains

I have a list which is defined as below:
def list1=["Test1","Test2","Test3"]
String str="Test2"
println("Found The String is:"+list1.contains(str));
//It is returning false even though there is a matching string.
What you've typed in there does work, so there's something else wrong. My guess is that you've done something like:
String part = "Test"
String str="Test2"
def list1=["${part}1","${part}2","Test3"]
def found = list1.contains(str)
in this case, found will be false... because:
"${'test'}" is not equal to "test", for some definitions of equal... even though printing them both makes you think so.
Here's why: Groovy different results on using equals() and == on a GStringImpl

Semantics and ambiguity of "returning" a value?

I was reading up on questions from a python quiz. Here is the following code and its respective question:
class Player(object):
def __init__(self, name, health):
self._name = name
self._health = health
def get_health(self):
"""Return the players health."""
## LINE ##
What is the required code for ## LINE ## so that the method satisfies the comment?
(a) print(self.health)
(b) return self.health
(c) print(self._health)
(d) return self._health
(e) More than one of the above is correct.
So, I'm wondering, is this question ambiguous?
If I state that a specific function's purpose is to "return the value of x", could that not be interpreted as both literally employing the return command to give x's value and using the print command to display the value.
Both give the same answer at face value in the interpreter.
Of course, things are different if you attempt to manipulate it indirectly:
get_health() * 5 yields a normal output if using return
get_health() * 5 yields an error if using print
So should I always treat 'return something' as actually using the return command?
I suppose print and return would both be viable only if the function's purpose said something like "Display the value in the python interpreter".
The correct answer is simply d): return self._health.
You almost answered your own question. Return in programming parlance means use of (the) return (Python/C/... statement, or an implicit return in other languages, etc).
The point here is that that the comment is meant for programmers, not users.
A print statement would imply something to the user running your program ("return output visible to the user"), but the user will not see or know about that comment.
And, as you already pointed out, the use of returning an actual value allows constructs like get_health() * 5.
Going one small step further, I would expect a printing function to be called print_health(); but that's up to the logic of the programming standard & style that is being used.

Resources