python-2.x

exec doesn't pick up variables from closure

谁说胖子不能爱 提交于 2019-12-01 02:55:41
问题 I'm a little curious why the following code raises a NameError . >>> s = """ ... foo = [1,2,3] ... def bar(): ... return foo[1] ... """ >>> namespace = {} >>> exec(s, {'__builtins__': None}, namespace) >>> print namespace {'foo': [1, 2, 3], 'bar': <function bar at 0x7f79871bd0c8>} >>> namespace['bar']() At the normal interpreter level, we can find foo in bar.func_globals or bar.func_closure if in a function. I guess I'm wondering why namespace['bar'] doesn't put foo in func_closure ... 回答1:

Relationship between pickle and deepcopy

给你一囗甜甜゛ 提交于 2019-12-01 02:15:52
What exactly is the relationship between pickle and copy.deepcopy ? What mechanisms do they share, and how? It is clear the two are closely-related operations, and share some of the mechanisms/protocols, but I can't wrap my head around the details. Some (confusing) things I found out: If a class defines __[gs]etstate__ , they get called upon a deepcopy of its instances. This surprised me at first, because I thought they are specific to pickle , but then I found that Classes can use the same interfaces to control copying that they use to control pickling . However, there's no documentation of

Why do new style class and old style class have different behavior in this case?

时光总嘲笑我的痴心妄想 提交于 2019-11-30 23:06:29
问题 I found something interesting, here is a snippet of code: class A(object): def __init__(self): print "A init" def __del__(self): print "A del" class B(object): a = A() If I run this code, I will get: A init But if I change class B(object) to class B() , I will get: A init A del I found a note in the __del__ doc: It is not guaranteed that del () methods are called for objects that still exist when the interpreter exits. Then, I guess it's because that B.a is still referenced(referenced by

dicts are not orderable in python 3?

放肆的年华 提交于 2019-11-30 20:59:54
Why are dicts orderable in python2, but not in python3? I can't find it anywhere in the documentation. Python 3.3.4 (default, Feb 11 2014, 16:14:21) >>> sorted([{'a':'a'},{'b':'b'}]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: dict() < dict() vs. Python 2.7.6 (default, Feb 26 2014, 12:01:28) >>> sorted([{'a':'a'},{'b':'b'}]) [{'a': 'a'}, {'b': 'b'} Martijn Pieters Python 2 uses an undocumented ordering , implemented as a .__cmp__() special method. The ordering only makes sense in a limited set of use-cases, and only exists because Python

Compare result from hexdigest() to a string

那年仲夏 提交于 2019-11-30 20:31:43
I've got a generated MD5-hash, which I would like to compare to another MD5-hash from a string. The statement below is false, even though they look the same when you print them and should be true. hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8" Google told me that I should encode the result from hexdigest() , since it doesn't return a string. However, the code below doesn't seem to work either. hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8") Python 2.7, .hexdigest() does return a str >>> hashlib.md5("foo").hexdigest() ==

Basic python arithmetic - division

左心房为你撑大大i 提交于 2019-11-30 20:31:21
I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 : >>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> print per_page 2 >>> pages = math.ceil(count/per_pages) >>> print pages 0.0 >>> pages = float(count/per_pages) >>> print pages 0.0 What am I doing wrong, and why math.ceil gives float number instead of int ? Python does integer division when both operands are integers, meaning that 1 / 2 is basically "how many times does

How does a Python custom comparator work?

喜夏-厌秋 提交于 2019-11-30 19:48:56
问题 I have the following Python dict: [(2, [3, 4, 5]), (3, [1, 0, 0, 0, 1]), (4, [-1]), (10, [1, 2, 3])] Now I want to sort them on the basis of sum of values of the values of dictionary, so for the first key the sum of values is 3+4+5=12. I have written the following code that does the job: def myComparator(a,b): print "Values(a,b): ",(a,b) sum_a=sum(a[1]) sum_b=sum(b[1]) print sum_a,sum_b print "Comparision Returns:",cmp(sum_a,sum_b) return cmp(sum_a,sum_b) items.sort(myComparator) print items

reorder byte order in hex string (python)

南楼画角 提交于 2019-11-30 19:12:48
I want to build a small formatter in python giving me back the numeric values embedded in lines of hex strings. It is a central part of my formatter and should be reasonable fast to format more than 100 lines/sec (each line about ~100 chars). The code below should give an example where I'm currently blocked. 'data_string_in_orig' shows the given input format. It has to be byte swapped for each word. The swap from 'data_string_in_orig' to 'data_string_in_swapped' is needed. In the end I need the structure access as shown. The expected result is within the comment. Thanks in advance Wolfgang R #

Python argparse: command-line argument that can be either named or positional

限于喜欢 提交于 2019-11-30 18:50:01
I am trying to make a Python program that uses the argparse module to parse command-line options. I want to make an optional argument that can either be named or positional. For example, I want myScript --username=batman to do the same thing as myScript batman . I also want myScript without a username to be valid. Is this possible? If so, how can it be done? I tried various things similar to the code below without any success. parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-u", "--user-name", default="admin") group.add_argument("user-name",

How to implement different levels for specific modules in Python

♀尐吖头ヾ 提交于 2019-11-30 17:57:58
From this stackoverflow question , how does one implement the following configuration file? [logger_qpid] level=NOTSET handlers=nullHandler qualname=qpid propagate=0 I am using logging.basicConfig: # Configure parser. parser = argparse.ArgumentParser(description = 'Allow for debug logging mode.') parser.add_argument('--debug', action = 'store_true', help = 'Outputs additional information to log.') c_args = parser.parse_args() # Configure logging mode. if c_args.debug: # Enable debug level of logging. print "Logging level set to debug." logging.basicConfig(filename = LOG_FILENAME, format = '%