yield

In there something similar to Java's Thread.yield() in Python? Does that even make sense?

北战南征 提交于 2019-12-04 03:38:32
I want to tell my Python threads to yield, and so avoid hogging the CPU unnecessarily. In Java, you could do that using the Thread.yield() function. I don't think there is something similar in Python, so I have been using time.sleep(t) where t = 0.00001 . For t=0 there seems to be no effect. I think that maybe there is something I am not understanding correctly about Python's threading model, and hence the reason for the missing thread.yield() . Can someone clarify this to me? Thanks! PS: This is what the documentation for Java's Thread.yield() says: Causes the currently executing thread

Issue with a python function returning a generator or a normal object

南楼画角 提交于 2019-12-04 03:25:12
问题 I defined the function f as def f(flag): n = 10 if flag: for i in range(n): yield i else: return range(n) But f returns a generator no matter what flag is: >>> f(True) <generator object f at 0x0000000003C5EEA0> >>> f(False) <generator object f at 0x0000000007AC4828> And if I iterate over the returned object: # prints normally for i in f(True): print(i) # doesn't print for i in f(False): print(i) It looks like f(False) returns a generator which has been iterated over. What's the reason? Thank

yield - statement or expression?

怎甘沉沦 提交于 2019-12-04 03:20:09
So, I've been reading this , and found out about sending values to generator. And now I'm kinda confused. Is yield a statement or an expression? It doesn't use parenthesis syntax, like functions, so it looks like statement. But it returns value, so it's like expression. Not so long ago I've had this conversation about "Why python doesn't have 'if x=foo(): (...)'?" (why can't we assign in if statement condition). I said, that statements are atomic, so assignment statement and if statement should be separated. Now, I don't know what to think anymore. == EDIT == I did my fair share of reading.

invoking yield for a generator in another function

*爱你&永不变心* 提交于 2019-12-04 02:56:53
suppose I have some manager object. This object's API has a main_hook function, that gets another function f as it's argument, and runs the given f in a loop, doing some stuff in between each iteration: def main_hook(self,f): while (self.shouldContinue()): #do some preparations f(self) #do some tear down Now, I also have (more accurately, would like to have ) a function stop_and_do_stuff , that once called, stops main_hook dead in it's tracks, returns the control to whichever func called main_hook , and after that func finished what's it doing, get control back to main_hook and continue.

Can yield produce multiple consecutive generators?

自作多情 提交于 2019-12-04 02:00:31
Here are two functions that split iterable items to sub-lists. I believe that this type of task is programmed many times. I use them to parse log files that consist of repr lines like ('result', 'case', 123, 4.56) and ('dump', ..) and so on. I would like to change these so that they will yield iterators rather than lists. Because the list may grow pretty large, but I may be able to decide to take it or skip it based on first few items. Also, if the iter version is available I would like to nest them, but with these list versions that would waste some memory by duplicating parts. But deriving

Is yield return in C# thread-safe?

假如想象 提交于 2019-12-03 22:12:46
I have the following piece of code: private Dictionary<object, object> items = new Dictionary<object, object>; public IEnumerable<object> Keys { get { foreach (object key in items.Keys) { yield return key; } } } Is this thread-safe? If not do I have to put a lock around the loop or the yield return ? Here is what I mean: Thread1 accesses the Keys property while Thread2 adds an item to the underlying dictionary. Is Thread1 affected by the add of Thread2? What exactly do you mean by thread-safe? You certainly shouldn't change the dictionary while you're iterating over it, whether in the same

ES6迭代器和生成器

心不动则不痛 提交于 2019-12-03 20:48:04
一、迭代器 JavaScript 原有的表示“集合”的数据结构,主要是数组(Array)和对象(Object),ES6 又添加了Map和Set。这样就需要一种统一的接口机制,来处理所有不同的数据结构。遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。 任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员) 。 1.Iterator的作用: 为各种数据结构,提供一个统一的、简便的访问接口; 使得数据结构的成员能够按某种次序排列 ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费。 2.原生具备iterator接口的数据(可用for of遍历) Array set容器 map容器 String 函数的 arguments 对象 NodeList 对象 let arr3 = [1, 2, 'kobe', true]; for(let i of arr3){ console.log(i); // 1 2 kobe true } let str = 'abcd'; for(let item of str){ console.log(item); // a b c d } function fun() { for (let i of arguments) {

迭代器与生成器

隐身守侯 提交于 2019-12-03 20:36:08
一、迭代器 迭代器可以理解为一种特殊的游标,是对循环遍历等一系列操作组成的一种抽象描述。而迭代器协议是程序的一种绑定关系,实现了该协议的对象称为可迭代对象。迭代器协议强调对象必须提供一个next或__next__()方法,并且执行该方法只有两种决策,要么返回迭代中的下一项,要么者引起一个StopIteration异常,以终止迭代。for循环的本质是循环所有对象,使用的一定是迭代器协议生成对象。因此for循环可以遍历所有的可迭代对象(字符串、列表、元组、字典、文件对象等)。既然如此,为什么我们定义一个序列的时候没有使用next方法呢?这是为什么呢?从理论上来讲,只有实现迭代器的对象才可称为可迭代对象。而我们在定义字符串、列表、元组、字典、文件对象的时候,本身没有给出next方法。从这种角度上来看,他们并没有遵循迭代器协议。但是平时我们为什么还是认为他们是可迭代对象呢? Python提供了一个可以让某种数据类型变为可迭代数据类型的方法,即让某种数据类型的对象直接调用__iter__()或iter()方法,此时我们再查看该数据类型的对象时就多出了next方法。下面如我们通过一个简单的实例来分析,我们使用字符窜调用__iter__()方法,然后使用可迭代对象调用next方法。 string = "hello world" myiter = string.__iter__() print

关于Python中的yield的理解

旧巷老猫 提交于 2019-12-03 17:34:56
生成器:yield表达式构成的函数就是生成器;每一个生成器都是一个迭代器(但是迭代器不一定是生成器)。return就是迭代器; yield 的功能类似于 return ,不同之处在于它返回的是 生成器 。 什么是生成器,你可以通俗的认为,在一个函数中,使用了yield来代替return的位置的函数,就是生成器。 它不同于函数的使用方法是:函数使用return来进行返回值,每调用一次,返回一个新加工好的数据返回给你;yield不同,它会在调用生成器的时候,把数据生成object,然后当你需要用的时候,要用next()方法来取,同时不可逆。 def test():    for i in range(1,10): yield i      #装入 ob = test()    #generator 类型 print next(ob) #1 释放的第一个装入的数据,(先入先出) print next(ob) #2 print next(ob) #3 print next(ob) #4 return:return可以终止函数的执行,也可以返回函数加工的数据,但是需要把数据存入内存中;return之后后面的将不再执行; yield:不会将所有数据取出来存入内存中;而是返回了一个对象;可以通过对象获取数据;用多少取多少,可以节省内容空间。 除了能返回一个值,还不会终止循环的运行; 来源:

Python destructor basing on try/finally + yield?

﹥>﹥吖頭↗ 提交于 2019-12-03 17:20:20
I've been testing a dirty hack inspired by this http://docs.python.org/2/library/contextlib.html . The main idea is to bring try/finally idea onto class level and get reliable and simple class destructor. class Foo(): def __init__(self): self.__res_mgr__ = self.__acquire_resources__() self.__res_mgr__.next() def __acquire_resources__(self): try: # Acquire some resources here print "Initialize" self.f = 1 yield finally: # Release the resources here print "Releasing Resources" self.f = 0 f = Foo() print "testing resources" print f.f But it always gives me: Initialize testing resources 1 and