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 Overflow
Discussions

a = b || c in Python - Stack Overflow
So in JavaScript (and probably other languages), you can assign a default value by using - a = b || c - This is mainly used inside a function but can be used outside of one. If b is undefined then ... More on stackoverflow.com
🌐 stackoverflow.com
python - What does "ABC" class do? - Stack Overflow
Stack Ads Connect your brand to the world’s most trusted technologist communities. Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. More on stackoverflow.com
🌐 stackoverflow.com
loops - For a, b in c, d Python - Stack Overflow
That said, you could skip the rigmarole ... and avoid the Python level loop entirely: ... or if mydict is an existing non-empty dict, use the update method, which accepts the same arguments as the constructor: ... Side-note: I renamed your variable to mydict, because shadowing built-in ... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
Python a, b = b, a +b - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... This is my first question and I started to learn Python... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
peps.python.org › pep-0651
PEP 651 – Robust Stack Overflow Handling | peps.python.org
Currently, if a program needs to deeply recurse it must manage the maximum recursion depth allowed, hopefully managing to set it in the region between the minimum needed to run correctly and the maximum that is safe to avoid a memory protection error. By separating the checks for C stack overflow from checks for recursion depth, pure Python programs can run safely, using whatever level of recursion they require.
Top answer
1 of 3
10

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.

2 of 3
4

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.abc submodule 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))
🌐
Medium
medium.com › @george.seif94 › 15-python-tips-and-tricks-so-you-dont-have-to-look-them-up-on-stack-overflow-90cec02705ae
15 Python tips and tricks, so you don’t have to look them up on Stack Overflow | by George Seif | Medium
February 11, 2022 - Here are 15 python tips and tricks to help you code faster! ... sentence_list = ["my", "name", "is", "George"] sentence_string = " ".join(sentence_list) print(sentence_string) sentence_string = "my name is George" sentence_string.split() print(sentence_string) [0]*1000 # List of 1000 zeros [8.2]*1000 # List of 1000 8.2's · x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y} ... def get_a_string(): a = "George" b = "is" c = "cool" return a, b, c sentence = get_a_string() (a, b, c) = sentence
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › tagged › python
Newest 'python' Questions - Stack Overflow
3 days ago - A FASTA file is a standard plain-text format in bioinformatics, used to store nucleotide or amino acid ... ... I have a while loop that is running 5000 times a second. Each time it runs it recalculates a whole ton of variables and then adds the value of a couple of those varibles to their own lists. After a ... ... Suppose I have 3 python dictionaries that look like this: 1: {a: ["j"], b: [True], c:["p", "x"]} 2: {a: ["j"], b: [False], c:["s", "t"]} 3: ...
Top answer
1 of 2
1

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

2 of 2
0

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)
Top answer
1 of 6
351

@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.

2 of 6
214

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.

Top answer
1 of 2
8

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
2 of 2
6

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.

🌐
Medium
martinxpn.medium.com › what-is-stack-overflow-really-40-100-days-of-python-e5e129416d33
What is Stack Overflow Really? (40/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - In Python, this error can occur due to several reasons: 1. Recursion depth: When a function calls itself repeatedly, and the conditions to exit the function are not met, the call stack gets filled, which can lead to stack overflow errors.
🌐
Reddit
reddit.com › r/learnpython › python stack overflow
r/learnpython on Reddit: Python Stack Overflow
July 5, 2021 -

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!

Top answer
1 of 12
1269

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, str uses 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 str as String and bytes as byte[];
  • SQL, think of str as NVARCHAR and bytes as BINARY or BLOB;
  • Windows registry, think of str as REG_SZ and bytes as REG_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.x str
  • str = '...' literals = sequences of confounded bytes/characters
    • Usually text, encoded in some unspecified encoding.
    • But also used to represent binary data like struct.pack output.

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).

2 of 12
547

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.

🌐
GNU
gnu.org › software › guile › manual › html_node › Stack-Overflow.html
Stack Overflow (Guile Reference Manual)
Most languages have a terrible stack overflow story. For example, in C, if you use too much stack, your program will exhibit “undefined behavior”, which if you are lucky means that it will crash. It’s especially bad in C, as you neither know ahead of time how much stack your functions use, nor the stack limit imposed by the user’s system, and the stack limit is often quite small relative to the total memory size. Managed languages like Python have a better error story, as they are defined to raise an exception on stack overflow – but like C, Python and most dynamic languages still have a fixed stack size limit that is usually much smaller than the heap.
🌐
GitHub
github.com › drathier › stack-overflow-import
GitHub - drathier/stack-overflow-import: Import arbitrary code from Stack Overflow as Python modules.
Import arbitrary code from Stack Overflow as Python modules. - drathier/stack-overflow-import
Starred by 3.7K users
Forked by 130 users
Languages   Python 100.0% | Python 100.0%
🌐
Stack Overflow
stackoverflow.com › questions › tagged › abc
Newest 'abc' Questions - Stack Overflow
As updates and changes are made to the repo, the models are not always backward compatible. I'm wondering if ... ... I was reading PEP-3119, and I discovered that builtins derive from ABCs. From PEP-3119: The built-in type set derives from MutableSet. The built-in type frozenset derives from Set and Hashable. In ... ... I'm trying to figure out in python whether virtual subclass will pass the static type check like mypy.