python-internals

Python 2 assumes different source code encodings

拜拜、爱过 提交于 2019-11-29 16:51:58
I noticed that without source code encoding declaration, the Python 2 interpreter assumes the source code is encoded in ASCII with scripts and standard input : $ python test.py # where test.py holds the line: print u'é' File "test.py", line 1 SyntaxError: Non-ASCII character '\xc3' in file test.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details $ echo "print u'é'" | python File "/dev/fd/63", line 1 SyntaxError: Non-ASCII character '\xc3' in file /dev/fd/63 on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details and it

scope of eval function in python

纵然是瞬间 提交于 2019-11-29 16:35:23
问题 Consider the following example: i=7 j=8 k=10 def test(): i=1 j=2 k=3 return dict((name,eval(name)) for name in ['i','j','k']) It returns: >>> test() {'i': 7, 'k': 10, 'j': 8} Why eval does not take into consideration the variables defined inside the function? From the documentation, optionally you can pass a globals and a locals dictionary. What does it means?Finally, how can I modify this small case to make it work? 回答1: Generators are implemented as function scopes: The scope of names

globals() vs locals() mutability

南笙酒味 提交于 2019-11-29 15:25:44
问题 In Python, globals() returns a representation of the global symbol table, while locals() returns a representation of the local state. While both return a dictionary, changes to globals() are effected in the global symbol table, while change to locals() have no effect. Why is this the case? 回答1: Function locals are highly optimised and determined at compile time, CPython builds on not being able to alter the known locals dynamically at runtime. You can see this when decoding a function

Source code for str.split?

天涯浪子 提交于 2019-11-29 15:23:50
I would like to see how str.split() is implemented in Python Here's what I tried: > inspect.getsource(str.split) TypeError: <method 'split' of 'str' objects> is not a module, class, method, function, traceback, frame, or code object Copying the other example on StackOverflow has not work: Code for Greatest Common Divisor in Python inspect.getsource(str.split) is not written to handle code written in the implementation language ( C here). str.split is builtin , i.e written in C . The source code for the implementation of str.split is broken up in two parts based on if a sep argument is supplied

Should importlib.reload restore a deleted attribute in Python 3.6?

风流意气都作罢 提交于 2019-11-29 14:51:08
I'm looking into these two related questions: here and here . I am seeing a behavior I do not expect in Python 3.6, which differs from behavior using plain reload in Python 2.7 (and 3.4). Namely, it seems that a module attribute that would be populated during module initialization or when re-exec-ing the module during a reload, is not restored after its local name is removed with del ... see below: For Python 3.6: In [1]: import importlib In [2]: import math In [3]: del math.cos In [4]: math.cos --------------------------------------------------------------------------- AttributeError

Using a function defined in an exec'ed string in Python 3 [duplicate]

馋奶兔 提交于 2019-11-29 13:22:47
This question already has an answer here: How does exec work with locals? 3 answers Why does the following python3 code produces an error? a=''' def x(): print(42) ''' class Test: def __init__(self): exec(a) x() t = Test() Results in this message: Traceback (most recent call last): File "bug.py", line 11, in <module> t = Test() File "bug.py", line 9, in __init__ x() NameError: global name 'x' is not defined Note: exec was just a Simple statement in Python 2.x, whereas it is a function in Python 3.x. Python 2.7 Let us check the changes made by executing a . class Test: def __init__(self): l, g

What is Python's sequence protocol?

♀尐吖头ヾ 提交于 2019-11-29 11:31:55
问题 Python does a lot with magic methods and most of these are part of some protocol. I am familiar with the "iterator protocol" and the "number protocol" but recently stumbled over the term "sequence protocol". But even after some research I'm not exactly sure what the "sequence protocol" is. For example the C API function PySequence_Check checks (according to the documentation) if some object implements the "sequence protocol". The source code indicates that this is a class that's not a dict

Why must Python list addition be homogenous?

痴心易碎 提交于 2019-11-29 10:57:47
问题 Can anyone familiar with Python's internals (CPython, or other implementations) explain why list addition is required to be homogenous: In [1]: x = [1] In [2]: x+"foo" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) C:\Users\Marcin\<ipython-input-2-94cd84126ddc> in <module>() ----> 1 x+"foo" TypeError: can only concatenate list (not "str") to list In [3]: x+="foo" In [4]: x Out[4]: [1, 'f', 'o', 'o'] Why shouldn't the x+

What makes lists unhashable?

萝らか妹 提交于 2019-11-29 10:25:49
So lists are unhashable: >>> { [1,2]:3 } TypeError: unhashable type: 'list' The following page gives an explanation: A list is a mutable type, and cannot be used as a key in a dictionary (it could change in-place making the key no longer locatable in the internal hash table of the dictionary). I understand why it is undesirable to use mutable objects as dictionary keys. However, Python raises the same exception even when I am simply trying to hash a list (independently of dictionary creation) >>> hash( [1,2] ) TypeError: unhashable type: 'list' Does Python do this as a guarantee that mutable

What happens when you try to delete a list element while iterating over it

岁酱吖の 提交于 2019-11-29 07:43:44
I'm iterating a list as follows: some_list = [1, 2, 3, 4] another_list = [1, 2, 3, 4] for idx, item in enumerate(some_list): del some_list[idx] for item in another_list: another_list.remove(item) When I print out the contents of the lists >>> some_list [2, 4] >>> another_list [2, 4] I'm aware that Python doesn't support modifying a list while iterating over it and the right way is to iterate over copy of list instead (so please don't downvote). But I want to know what exactly happens behind the scenes i.e. Why is the output of the above snippet [2, 4] ? You can use a self-made iterator that