My favorite Py 3.6 features

1.Underscores in numeric literals

 

>>> bill = 10_000
>>> print(bill + bill * 0.12)
11200.0

1.Underscores in numeric literals

 

>>> print("{:_}".format(bill + bill * 0.12))
11_200.0

1.Underscores in numeric literals

 

>>> 100_000 + 1_0
100010

>>> flags = 0b_0011_1111_0100_1110
>>> flags
16206

1.Underscores in numeric literals

 

>>> 1_0_0
100

>>> bill = 1_0__000
  File "<stdin>", line 1
    bill = 1_0__000
              ^
SyntaxError: invalid token

PEP 515: https://www.python.org/dev/peps/pep-0515/

2.Formatted string literals

 

>>> f"your bill is {bill}"
'your bill is 10000'
>>> f"your bill is {bill:_}"
'your bill is 10_000'

2.Formatted string literals

 

>>> langs = ['Python', 'Erlang', 'Rust']
>>> f'Long time favorite {langs[0]}. Recent addiction {langs[1]}, {langs[2]}'
'Long time favorite Python. Recent addiction Erlang, Rust'



>>> now = datetime.datetime.now()
>>> f'Presentation prepared on {now.day}-{now.month}-{now.year} {now.hour}:{now.minute}'
'Presentation prepared on 17-2-2017 19:7'

2.Formatted string literals

 

>>> f"Total cost { bill + bill * 0.12}"
'Total cost 11200.0'

>>> f"Total cost { bill + bill * 0.12: _}"
'Total cost  11_200.0'

2.Formatted string literals

 

>>> class A:
...     class_var = 23
... 
>>> f'Accessing class_var: {A.class_var}'
'Accessing class_var: 23'

>>> f'Accessing class_var: {A().class_var}'
'Accessing class_var: 23'

PEP 498: https://www.python.org/dev/peps/pep-0498/

3. Secret!

>>> import secrets

>>> secrets.token_bytes(16)
b'\x95pv`\xfaG\x9f\xd3p\xee\xf8\x9b\x98~\xbeQ'
>>> secrets.token_hex(16)
'a59762b3748ff460f33e559e32708c8b'
>>> secrets.token_urlsafe(16)
'q5lzEemVBbbSAfvnVcNHpw'

PEP 506: https://www.python.org/dev/peps/pep-0506/

4. Async Comprehension

# https://www.blog.pythonlibrary.org/2017/02/14/whats-new-in-python-asynchronous-comprehensions-generators/
import asyncio


async def numbers(numbers):
    for i in range(numbers):
        yield i
        await asyncio.sleep(0.5)


async def main():
    odd_numbers = [i async for i in numbers(10) if i % 2]
    print(odd_numbers)


if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(main())
    finally:
        event_loop.close()


4. Async Comprehension

$time python3.6 async_comp.py 
[1, 3, 5, 7, 9]
5.181 secs

PEP 530: https://www.python.org/dev/peps/pep-0530/

Thank You

My favorite Py 3.6 features

By Kracekumar

My favorite Py 3.6 features

  • 1,616