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 '返回值\n'
 
  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中。

 

內容自編及網上文檔查找,未完待續


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM