python语言的方向

本人一直主要从事python,java后端开发偶尔也会写一些前端等。个人谈一谈python语言的优缺点及之后的方向(个人想法,不喜勿喷)

个人观点:

  1. 众所周知,python的优点是动态强类型语言,便捷。拥有丰富得三方库,使人们在使用得时候不再需要关注底层的实现,专注于业务的开发

  2. 有很多说python语言漏洞大,不如java等,个人觉得纯属无稽之谈,python丰富的扩展库可以实现java的接口,函数不同参数对应相同函数的调用。传参类型可指定:demo: str 等等。说漏洞大的不如去总结自己的代码能力不行。任何语言写出来的代码都不能保证无bug,bug的多少取决与程序员的能力,而不是语言。相比于评价一门语言的好坏,不如总结这门语言更适合做什么,语言只是你实现业务的方式,仅此而已

  3. 相对于其他语言,py语法更便捷。可使用更少的代码,或者说可以更高效的实现功能。如上都是优点,难道py就没有缺点嘛? 有的。这就是我想说的py的未来在哪里:编译型语言与解释型语言相比较的毙命就是效率问题,所以py一直在优化效率问题。解决效率的方法大多都是去考虑:串行,并行,并发等等机制,分析问题:多进程,多线程等最优化,或者考虑功能解耦,集群,微服务分布式。前端亦然,缓存数据,懒加载,CDN等。获取有人会抬杠说pyc的问题,但事实上大多数开发并不会那么做,不是嘛?

  4. 如上所说都是功能及架构层次的设计及改动,有没有其他代码层级及py迭代内容的性能升级那? 答案是有的,py自3.x版本之后,后期走的都是性能优化,主打的就是异步编程。个人觉得目前py的未来及之后的方向都在于提升效率的异步编程

  5.虽然本人希望以后的方向是java,但只是因为对于大多数达不到py极致的人们(我自己)来说,java的工作机会更多。对于喜爱及写代码的丝滑感,更倾向于py,因为py更简洁,亲近新手

下面我先来讲一下异步的概念:

  异步是和同步相对的,异步是指在处理调用这个事务的之后,不会等待这个事务的处理结果,直接处理第二个事务去了,通过状态、通知、回调来通知调用者处理结果。

在Python3.5中,引入了aync&await 语法结构,通过"aync def"可以定义一个协程代码片段,作用类似于Python3.4中的@asyncio.coroutine修饰符,而await则相当于"yield from"。

  import time

  def hello():
    ime.sleep(1)

  def run():
    for i in range(5):
      hello()
      print('Hello World:%s' % time.time()) # 任何伟大的代码都是从Hello World 开始的!
  if __name__ == '__main__':
    run()

如上述代码,则会阻塞,等待每一个函数执行完毕再去执行下一次

  import time
  import asyncio

  # 定义异步函数
  async def hello():
    asyncio.sleep(1)
    print('Hello World:%s' % time.time())

  def run():
    for i in range(5):
    loop.run_until_complete(hello())

  loop = asyncio.get_event_loop()
  if __name__ =='__main__':
    run()

如上述代码则不会阻塞之后的执行,原因如下:async def 用来定义异步函数,其内部有异步操作。每个线程有一个事件循环,主线程调用asyncio.get_event_loop()时会创建事件循环,你需要把异步的任务丢给这个循环的run_until_complete()方法,事件循环会安排协同程序的执行。

await关键字: 

  import asyncio
  async def func():
    print("来玩呀!!")
    # await 等待 2秒
    response = await asyncio.sleep(2)
    print("结束", response)
 
  loop = asyncio.get_event_loop()
  loop.run_until_complete(func())
 
 
# 遇到IO操作挂起当前协程(任务),等待IO操作完成之后再继续往下执行
  import asyncio
 
  async def others():
    print("start")
    await asyncio.sleep(2)
    print("end")
    return '返回值 '
 
  async def func():
    print("开始了!!!")
    # 遇到IO操作挂起当前协程(任务),等待IO操作完成之后再继续往下执行
    response = await others()
    print("结束", response)
 
 
  loop = asyncio.get_event_loop()
  loop.run_until_complete(func())
 
 
创建Task对象 将当前的执行func函数执行到事件循环中
  import asyncio 
 
  async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "返回值"
 
  async def main():
    print("main开始")
    # 创建Task对象 将当前的执行func函数执行到事件循环中
    task1 = asyncio.create_task(func())
    # 创建Task对象 将当前的执行func函数执行到事件循环中
    ask2 = asyncio.create_task(func())
    print("main结束")
 
    # 当执行协程遇到IO操作时, 会自动化切换执行其他任务
    # 此处的await是等待相对应的协程全都执行完毕并获取结果
    res1 = await task1
    res2 = await task2
    print(res1, res2)
 
  loop = asyncio.get_event_loop()
  loop.run_until_complete(main())
 
也可以换其他的task执行方式 
  async def main():
    print("main开始")
    task_list = [
    # name 可以赋值 name
    asyncio.create_task(func(), name='a1'),
    asyncio.create_task(func(), name='a2')
    ]
    print("main结束")
 
    # 当执行协程遇到IO操作时, 会自动化切换执行其他任务
    # 此处的await是等待相对应的协程全都执行完毕并获取结果
    # done 如果两个完成之后 就会放到 done中 set类型
    # timeout 等待 多少秒 pending 就是 等待没有完成的 默认值 是 None
    done, pending = await asyncio.wait(task_list, timeout=None)
    print(done, pending)
 
 
异步Mysql:
  import aiomysql
  import asyncio
 
  # 因为 aiomysql 必须要这个loop参数
  async def create_base(loop):
    poll = aiomysql.create_pool(
    host='127.0.0.1',
    port=3306,
    user="root",
    password="python123",
    db="aiomysql01",
    loop=loop
    )
    async with poll.acquire() as conn:
      async with conn.cursor() as cursor:
        print(cursor)
 
  if __name__ == '__main__':
    my_loop = asyncio.get_event_loop()
    my_loop.run_until_complete(create_base(loop=my_loop))
 
 

异步上下文管理器”async with”

异步上下文管理器指的是在enterexit方法处能够暂停执行的上下文管理器。

为了实现这样的功能,需要加入两个新的方法:__aenter__ 和__aexit__。这两个方法都要返回一个 awaitable类型的值。

异步上下文管理器的一种使用方法是:

  class AsyncContextManager:

    async def __aenter__(self):

      await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):

      await log('exiting context')

新语法

异步上下文管理器使用一种新的语法:

  async with EXPR as VAR:

    BLOCK

这段代码在语义上等同于:

  mgr = (EXPR)

  aexit = type(mgr).__aexit__

  aenter = type(mgr).__aenter__(mgr)

  exc = True

  VAR = await aenter

  try:

    BLOCK

  except: if not await aexit(mgr, *sys.exc_info()):

    raise

  else:

    await aexit(mgr, None, None, None)

和常规的with表达式一样,可以在一个async with表达式中指定多个上下文管理器。

如果向async with表达式传入的上下文管理器中没有__aenter__ 和__aexit__方法,这将引起一个错误 。如果在async def函数外面使用async with,将引起一个SyntaxError(语法错误)。

异步迭代器 “async for”

一个异步可迭代对象(asynchronous iterable)能够在迭代过程中调用异步代码,而异步迭代器就是能够在next方法中调用异步代码。为了支持异步迭代:

1、一个对象必须实现__aiter__方法,该方法返回一个异步迭代器(asynchronous iterator)对象。
2、一个异步迭代器对象必须实现__anext__方法,该方法返回一个awaitable类型的值。
3、为了停止迭代,__anext__必须抛出一个StopAsyncIteration异常。

异步迭代的一个例子如下:

  class AsyncIterable:

    def __aiter__(self):

      return self async

    def __anext__(self):

      data = await self.fetch_data()

      if data:

        return data

      else:

        raise StopAsyncIteration

    async def fetch_data(self):

       ...

新语法

通过异步迭代器实现的一个新的迭代语法如下:

async for TARGET in ITER:

  BLOCK

else:

  BLOCK2

这在语义上等同于:

  iter = (ITER)

  iter = type(iter).__aiter__(iter)

  running = True

  while running:

    try:

      TARGET = await type(iter).__anext__(iter)

    except StopAsyncIteration:

      running = False

    else:

      BLOCK

  else:

    BLOCK2

把一个没有__aiter__方法的迭代对象传递给 async for将引起TypeError。如果在async def函数外面使用async with,将引起一个SyntaxError(语法错误)。

和常规的for表达式一样, async for也有一个可选的else 分句。

例子1

使用异步迭代器能够在迭代过程中异步地缓存数据:

async for data in cursor:

   ...

下面的语法展示了这种新的异步迭代协议的用法:

  class Cursor:

    def __init__(self):

      self.buffer = collections.deque()

    async def _prefetch(self):

      ...

    def __aiter__(self):

      return self

    async def __anext__(self):

      if not self.buffer:

        self.buffer = await self._prefetch()

        if not self.buffer:

          raise StopAsyncIteration

      return self.buffer.popleft()

接下来这个Cursor 类可以这样使用:

  async for row in Cursor():

    print(row)

相当于以下代码

  i = Cursor().__aiter__()

  while True:

    try:

      row = await i.__anext__()

    except StopAsyncIteration:

      break

    else:

      print(row)

例子2

下面的代码可以将常规的迭代对象变成异步迭代对象。尽管这不是一个非常有用的东西,但这段代码说明了常规迭代器和异步迭代器之间的关系。

  class AsyncIteratorWrapper:

    def __init__(self, obj):

      self._it = iter(obj)

    def __aiter__(self):

      return self

    async def __anext__(self):

      try:

        value = next(self._it)

      except StopIteration:

        raise StopAsyncIteration

      return value

  async for letter in AsyncIteratorWrapper("abc"):

    print(letter)

为什么要抛出StopAsyncIteration?

协程(Coroutines)内部仍然是基于生成器的。因此在PEP 479之前,下面两种写法没有本质的区别:

def g1():

  yield from fut

  return 'spam'

def g2():

  yield from fut

  raise StopIteration('spam')

自从 PEP 479 得到接受并成为协程 的默认实现,下面这个例子将StopIteration包装成一个RuntimeError

async def a1():

  await fut

  raise StopIteration('spam')

告知外围代码迭代已经结束的唯一方法就是抛出StopIteration。因此加入了一个新的异常类StopAsyncIteration

由PEP 479的规定 , 所有协程中抛出的StopIteration异常都被包装在RuntimeError中。

内容自编及网上文档查找,未完待续

原文地址:https://www.cnblogs.com/hanzeng1993/p/15065336.html