This is just a way to declare a and b as equal to c.
>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2
So you can use as much as you want:
>>> i=7
>>> a=b=c=d=e=f=g=h=i
You can read more in Multiple Assignment from this Python tutorial.
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.
There is also another fancy thing! You can swap values like this: a,b=b,a:
>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2
Answer from fedorqui on Stack OverflowThis is just a way to declare a and b as equal to c.
>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2
So you can use as much as you want:
>>> i=7
>>> a=b=c=d=e=f=g=h=i
You can read more in Multiple Assignment from this Python tutorial.
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.
There is also another fancy thing! You can swap values like this: a,b=b,a:
>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2
python support multi variable assignment at a time called multiassignment.
In [188]: a = b = c = d = 4
In [189]: a
Out[189]: 4
In [190]: b
Out[190]: 4
In [191]: c
Out[191]: 4
In [192]: d
Out[192]: 4
In [193]: a = 2
In [194]: b = 2
is same as for immutable object
In [195]: a, b = 2 #int is a immutable object like `tuple`, `str`
while this is not to be mean for mutable object like list, dictionary
read about mutable and immutable
s.accept() returns a tuple of two values : (host, port).
Therefore,
conn, address = s.accept()
is (apart that accept() is called twice) the same as
conn, address = s.accept()[0], s.accept()[1]
when receiving a tuple you can unpack(or "split") it into its members by using this syntax:
member1, member2, member3 = tuple
or
member1, member2 member3 = (member1, member2 member3)
in your case you are receiving a tuple of the form (connection, address), so to unpack it into two variables you write:
conn, address = s.accept()
It's equivalent to this:
returned_tuple = s.accept()
conn, address = returned_tuple
a = b || c in Python - Stack Overflow
python - What does "ABC" class do? - Stack Overflow
loops - For a, b in c, d Python - Stack Overflow
Python a, b = b, a +b - Stack Overflow
Videos
In many languages some values evaluate to False. In Python this is False, None, 0, 0.0, [], (), {}, '' and every object, that has a special method which evaluates to False.
In your description you only want to fill a list up to 3 elements. This can be done with:
a, b, c = s + [0,9,1][len(s):]
I don't think this works particularly elegantly in Python - you need to consider what happens when the list is too short and you need to distinguish between None (often used to indicate "doesn't exist") and 0 (which also evaluates to False).
You could use
a = s[0] if (len(s)>0 and s[0] is not None) else 0
It isn't really an elegant idiomatic one-liner though, and you have to remember to write the index of s three times.
Alternatively
# defined once
def get_default(s,idx,default):
return s[idx] if (len(s)>idx and s[idx] is not None) else default
a = get_default(s,0,0)
b = get_default(s,1,9)
...
might do if you're going to be doing this a lot, and always using lists. I think this may just be a case where what works in Javascript doesn't quite work in Python though, and you have to live with that.
SubQuery is an abstract base class (per the abc module) with one or more abstract methods that you did not override. By adding ABC to the list of base classes, you defined ValueSum itself to be an abstract base class. That means you aren't forced to override the methods, but it also means you cannot instantiate ValueSum itself.
PyCharm is warning you ahead of time that you need to implement the abstract methods inherited from SubQuery; if you don't, you would get an error from Python when you actually tried to instantiate ValueSum.
As to what inheriting from ABC does, the answer is... not much. It's a convenience for setting the metaclass. The following are equivalent:
class Foo(metaclass=abc.ABCMeta):
...
and
class Foo(abc.ABC):
...
The metaclass modifies __new__ so that every attempt to create an instance of your class checks that the class has implemented all methods decorated with @abstractmethod in a parent class.
The 'Abstract Base classes" or abc.ABC is a helper class
https://docs.python.org/3/library/abc.html
Here's a snippet of why they exist:
The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the
collections.abcsubmodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.
A good example here: https://pymotw.com/2/abc/ | https://pymotw.com/3/abc/
From pymotw:
Forgetting to set the metaclass properly means the concrete implementations do not have their APIs enforced. To make it easier to set up the abstract class properly, a base class is provided that sets the metaclass automatically.
abc_abc_base.py
import abc
class PluginBase(abc.ABC):
@abc.abstractmethod
def load(self, input):
"""Retrieve data from the input source
and return an object.
"""
@abc.abstractmethod
def save(self, output, data):
"""Save the data object to the output."""
class SubclassImplementation(PluginBase):
def load(self, input):
return input.read()
def save(self, output, data):
return output.write(data)
if __name__ == '__main__':
print('Subclass:', issubclass(SubclassImplementation,
PluginBase))
print('Instance:', isinstance(SubclassImplementation(),
PluginBase))
You want the zip function to make a generator of tuples of values from each of a number of inputs:
mydict = {}
for key, value in zip(listKeys, listValues):
mydict[key] = value
That said, you could skip the rigmarole of writing your own loop and let the dict constructor do the work; it can take an iterable of key/value pairs to initialize itself, and avoid the Python level loop entirely:
mydict = dict(zip(listKeys, listValues))
or if mydict is an existing non-empty dict, use the update method, which accepts the same arguments as the constructor:
mydict.update(zip(listKeys, listValues))
Side-note: I renamed your variable to mydict, because shadowing built-in names like dict is a terrible, terrible idea.
Iterate through two lists simultaneously using zip :
for key, value in zip(listKeys, listValues) :
dict[key] = value
In a, b = b, a + b, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:
c = a + b
a = b
b = c
In the second example, the value of a has already been changed by the time b = a + b is run. Hence, the result is different.
The line:
a, b = b, a + b
is closer to:
temp_a = a
a = b
b = temp_a + b
where b is using the old value of a before a was reassigned to the value of b.
Python first evaluates the right-hand expression and stores the results on the stack, then takes those two values and assigns them to a and b. That means that a + b is calculated before a is changed.
See How does swapping of members in the python tuples (a,b)=(b,a) work internally? for the low-down on how this all works, at the bytecode level.
First, this does not work...
a = [john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]
because it is not python valid syntax. So I assume you mean
a = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"
We can split it into parts on a separator... The default seperator is space " " now our code is
s = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"
s = s.replace("[", "").replace("]", "")
s = s.replace(",", " ")
a = s.split()
print(s)
print(a)
and we get printed
[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]
['[john', 'jr', '0,', 'Akbar', 'AK', '1001,', 'doctor', 'rd', '9999,', 'Mohammedans', 'med', '1000,', 'pat', 'mat', '200,', 'cajole', 'Jul', '21]']
A bit hard to read and you probably don't want the leading and trailing brackets so we strip those. the commas are going to cause number parsing errors so we replace those with spaces. Since spaces are the separator and we want any parts like 12,hi with no space to become 12 hi
Next lets find all the numbers and add those up. We have to simply try to parse each string as a number see if it succeeds.
s = "[john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200, cajole Jul 21]"
s = s.replace("[", "").replace("]", "")
s = s.replace(",", " ")
a = s.split()
print(s)
print(a)
mysum = 0.0
for w in a:
print("Word is %s" % (w,))
try:
n = float(w)
print("Found number %f" % (n,))
mysum += n
except:
# Ignore any exceptions
pass
print("Sum is %f" %(mysum,))
pass
And we get
john jr 0 Akbar AK 1001 doctor rd 9999 Mohammedans med 1000 pat mat 200 cajole Jul 21
['john', 'jr', '0', 'Akbar', 'AK', '1001', 'doctor', 'rd', '9999', 'Mohammedans', 'med', '1000', 'pat', 'mat', '200', 'cajole', 'Jul', '21']
Word is john
Word is jr
Word is 0
Found number 0.000000
Word is Akbar
Word is AK
Word is 1001
Found number 1001.000000
Word is doctor
Word is rd
Word is 9999
Found number 9999.000000
Word is Mohammedans
Word is med
Word is 1000
Found number 1000.000000
Word is pat
Word is mat
Word is 200
Found number 200.000000
Word is cajole
Word is Jul
Word is 21
Found number 21.000000
Sum is 12221.000000
So now we have working code that meets what you stated, it finds the numbers and adds them. But is this maintainable and efficient and functional etc. When I have the above problem I use some methods I made that make it easier. Here they are.
def tryParseInt(value=None, default_value=0):
"""
Try to parse a string value to an int. Returns the value and True
e.g. tryParseInt("42", 7) returns (42, True)
tryParseInt("abcdef", 7) returns (7, False)
See twit_test.py
"""
try:
return int(value), True
except (ValueError, TypeError):
return default_value, False
def tryParseFloat(value=None, default_value=0.0):
"""
Try to parse a string value to an float. Returns the value and True
e.g. tryParseInt("42.42", 7.3) returns (42.42, True)
tryParseInt("abcdef", 7.3) returns (7.3, False)
See twit_test.py
"""
try:
return float(value), True
except (ValueError, TypeError):
return default_value, False
def split_strip(s: str, sep=' '):
"""
Split s into parts on delimiter, then strip the sub strings and remove any blanks.
Never returns None.
Returns an array of the sub strings. The returned array my be empty.
See twit_test.py for examples.
"""
if s is None:
return []
parts = s.split(sep=sep)
ret = []
if parts is not None:
for ss in parts:
sss = ss.strip()
if len(sss) > 0:
ret.append(sss)
return ret
The above helpers are available on GitHib project https://github.com/RMKeene/twit
I don't know english very well, but I think this is waht you expected
L = 'john jr 0, Akbar AK 1001, doctor rd 9999, Mohammedans med 1000, pat mat 200,
cajole Jul 21'
L = L.split(',')
Sum_L = 0
for i in range(0,len(L)):
L[i] = (L[i].strip()).split(' ')
Sum_L = Sum_L + int(L[i][2])
print(Sum_L)
@Oddthinking's answer is not wrong, but I think it misses the real, practical reason Python has ABCs in a world of duck-typing.
Abstract methods are neat, but in my opinion they don't really fill any use-cases not already covered by duck typing. Abstract base classes' real power lies in the way they allow you to customise the behaviour of isinstance and issubclass. (__subclasshook__ is basically a friendlier API on top of Python's __instancecheck__ and __subclasscheck__ hooks.) Adapting built-in constructs to work on custom types is very much part of Python's philosophy.
Python's source code is exemplary. Here is how collections.Container is defined in the standard library (at time of writing):
class Container(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
This definition of __subclasshook__ says that any class with a __contains__ attribute is considered to be a subclass of Container, even if it doesn't subclass it directly. So I can write this:
class ContainAllTheThings(object):
def __contains__(self, item):
return True
>>> issubclass(ContainAllTheThings, collections.Container)
True
>>> isinstance(ContainAllTheThings(), collections.Container)
True
In other words, if you implement the right interface, you're a subclass! ABCs provide a formal way to define interfaces in Python, while staying true to the spirit of duck-typing. Besides, this works in a way that honours the Open-Closed Principle.
Python's object model looks superficially similar to that of a more "traditional" OO system (by which I mean Java*) - we got yer classes, yer objects, yer methods - but when you scratch the surface you'll find something far richer and more flexible. Likewise, Python's notion of abstract base classes may be recognisable to a Java developer, but in practice they are intended for a very different purpose.
I sometimes find myself writing polymorphic functions that can act on a single item or a collection of items, and I find isinstance(x, collections.Iterable) to be much more readable than hasattr(x, '__iter__') or an equivalent try...except block. (If you didn't know Python, which of those three would make the intention of the code clearest?)
That said, I find that I rarely need to write my own ABC and I typically discover the need for one through refactoring. If I see a polymorphic function making a lot of attribute checks, or lots of functions making the same attribute checks, that smell suggests the existence of an ABC waiting to be extracted.
*without getting into the debate over whether Java is a "traditional" OO system...
Addendum: Even though an abstract base class can override the behaviour of isinstance and issubclass, it still doesn't enter the MRO of the virtual subclass. This is a potential pitfall for clients: not every object for which isinstance(x, MyABC) == True has the methods defined on MyABC.
class MyABC(metaclass=abc.ABCMeta):
def abc_method(self):
pass
@classmethod
def __subclasshook__(cls, C):
return True
class C(object):
pass
# typical client code
c = C()
if isinstance(c, MyABC): # will be true
c.abc_method() # raises AttributeError
Unfortunately this one of those "just don't do that" traps (of which Python has relatively few!): avoid defining ABCs with both a __subclasshook__ and non-abstract methods. Moreover, you should make your definition of __subclasshook__ consistent with the set of abstract methods your ABC defines.
Short version
ABCs offer a higher level of semantic contract between clients and the implemented classes.
Long version
There is a contract between a class and its callers. The class promises to do certain things and have certain properties.
There are different levels to the contract.
At a very low level, the contract might include the name of a method or its number of parameters.
In a staticly-typed language, that contract would actually be enforced by the compiler. In Python, you can use EAFP or type introspection to confirm that the unknown object meets this expected contract.
But there are also higher-level, semantic promises in the contract.
For example, if there is a __str__() method, it is expected to return a string representation of the object. It could delete all contents of the object, commit the transaction and spit a blank page out of the printer... but there is a common understanding of what it should do, described in the Python manual.
That's a special case, where the semantic contract is described in the manual. What should the print() method do? Should it write the object to a printer or a line to the screen, or something else? It depends - you need to read the comments to understand the full contract here. A piece of client code that simply checks that the print() method exists has confirmed part of the contract - that a method call can be made, but not that there is agreement on the higher level semantics of the call.
Defining an Abstract Base Class (ABC) is a way of producing a contract between the class implementers and the callers. It isn't just a list of method names, but a shared understanding of what those methods should do. If you inherit from this ABC, you are promising to follow all the rules described in the comments, including the semantics of the print() method.
Python's duck-typing has many advantages in flexibility over static-typing, but it doesn't solve all the problems. ABCs offer an intermediate solution between the free-form of Python and the bondage-and-discipline of a staticly-typed language.
You can cause a stack overflow quite easily in python, as in any other language, by building an infinately recursive funcion. This is easier in python as it doesn't actually have to do anything at all other than be recursive.
>>> def foo():
... return foo()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
.......
File "<stdin>", line 2, in foo
RuntimeError: maximum recursion depth exceeded
>>>
As for the heap, that is managed by a garbage collector. You can allocate lots of objects and eventually run out of heap space and Python will raise a MemoryError, but it's going to take a fair amount of time. You actually did that with your 'stack overflow' example in the question. You stored a reference to a string on the stack, this string took up all the free memory available to the process. As a rule of thumb, Python stores a reference to a heap structure on the stack for any value that it can't guarantee the size of.
As for how it all works, from the fist example you can see that python has a built-in limit to the depth of the call stack that it will not exceed. The amount of memory available for heap space is defined by the OS however and will depend upon many factors.
These are should be the appropriate parts of the python docs for infomation on the errors themselves:
- http://docs.python.org/release/3.2.3/library/exceptions.html#RuntimeError
- http://docs.python.org/release/3.2.3/library/exceptions.html#MemoryError
please correct me if wrong:
As far as I know, when it comes to actual stack implementation, the python stack (in the default distribution) is actually based in the heap memory (memory allocated with malloc). So you cannot cause the stack overflow, but you can run out of memory. The computer slowdown you seen is because memory is being swapped to disk, very slow procedure.
generally, you have no idea how the interpreted/byte-compiled language implements its stack, but most like it is not implemented in the stack memory, so you cannot cause stack overflow. it is possible to implement Python using alloca, but why?
Cf. CPython - Internally, what is stored on the stack and heap?
Try the same experiment with compiled language, C++, Fortran, etc. which compiles to machine code.
so i am sort of a python developer, i am an automation developer, my job is to automate tests, create framework etc.
but i find that i keep using stackoverflow a lot, question is am i still a programmer if i keep using stack overflow a lot?
Hello! I am new to python. I created a script/bot, and its function is work until closed.
That bot has a main() function that one way or another calls itself after a 1 minute timer.
After some time i noticed that it crashed and closed Tested again but now in Visual Studio Code and after 18 hours it crashed again with fatal error stack overflow.
Went in and created a separate script with a main function calling itself and after 1035 loops it caused stack overflow. Now 1035*1minute is about 18 hours.
How can i create an infinite script without causing stack overflow?
Thanks!
Python 3.x makes a clear distinction between the types:
str='...'literals = a sequence of characters. A “character” is a basic unit of text: a letter, digit, punctuation mark, symbol, space, or “control character” (like tab or backspace). The Unicode standard assigns each character to an integer code point between 0 and 0x10FFFF. (Well, more or less. Unicode includes ligatures and combining characters, so a string might not have the same number of code points as user-perceived characters.) Internally,struses a flexible string representation that can use either 1, 2, or 4 bytes per code point.bytes=b'...'literals = a sequence of bytes. A “byte” is the smallest integer type addressable on a computer, which is nearly universally an octet, or 8-bit unit, thus allowing numbers between 0 and 255.
If you're familiar with:
- Java or C#, think of
strasStringandbytesasbyte[]; - SQL, think of
strasNVARCHARandbytesasBINARYorBLOB; - Windows registry, think of
strasREG_SZandbytesasREG_BINARY.
If you're familiar with C(++), then forget everything you've learned about char and strings, because a character is not a byte. That idea is long obsolete.
You use str when you want to represent text.
print('שלום עולם')
You use bytes when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str to a bytes object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes into a str.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...' notation is somewhat confusing in that it allows the printable range of ASCII characters i.e. character code 32 - 126 (space " " up to tilde "~") to be used as a shorthand directly instead of their hex values (0x20 up to 0x7E)
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
In Python 2.x
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode=u'...'literals = sequence of Unicode characters = 3.xstrstr='...'literals = sequences of confounded bytes/characters- Usually text, encoded in some unspecified encoding.
- But also used to represent binary data like
struct.packoutput.
In order to ease the 2.x-to-3.x transition, the b'...' literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes in 3.x) from text strings (which should be str in 3.x). The b prefix does nothing in 2.x, but tells the 2to3 script not to convert it to a Unicode string in 3.x.
So yes, b'...' literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
The r prefix creates a raw string (e.g., r'\t' is a backslash + t instead of a tab), and triple quotes '''...''' or """...""" allow multi-line string literals.
The f prefix (introduced in Python 3.6) creates a “formatted string literal” which can reference Python variables. For example, f'My name is {name}.' is shorthand for 'My name is {0}.'.format(name).
To quote the Python 2.x documentation:
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.
The Python 3 documentation states:
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.