Skip to content

Instantly share code, notes, and snippets.

@yubessy
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yubessy/14d3b460d6376522f9d9 to your computer and use it in GitHub Desktop.
Save yubessy/14d3b460d6376522f9d9 to your computer and use it in GitHub Desktop.
あまり知られていないPythonの言語仕様(Python3.4以降対応) ref: http://qiita.com/yubessy/items/bfcce577e2266ce86641
>>> c1 = 1 + 1j
>>> c2 = 1 - 2j
>>> c1 + c2
(2-1j)
>>> c1 * c2
(3-1j)
>>> c1 / c2
(-0.2+0.6j)
>>> a = range(3)
>>> b = range(4)
>>> [x + y for x in a for y in b]
[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5]
>>> def singleton(cls):
... instances = {}
... def getinstance(*args, **kwargs):
... if cls not in instances:
... instances[cls] = cls(*args, **kwargs)
... return instances[cls]
... return getinstance
...
>>> @singleton
... class C(object):
... pass
...
>>> c1 = C()
>>> c2 = C()
>>> c1 is c2
True
>>> def g():
... yield from range(5)
... yield from range(5, 10)
...
>>> [i for i in g()]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> try:
... raise Exception('e1') from Exception('e2')
... except Exception as e:
... print(e.__cause__)
...
e2
>>> a = list(range(20))
>>> a[::2]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> a = range(10)
>>> b = a
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b is a # bとaは同一のオブジェクト
True
>>> c = a[:]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> c is a # bとaは別個のオブジェクト
False
>>> ...
Ellipsis
>>> bool(...)
True
>>> def f(a, *, b):
... pass
...
>>> f(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: f() missing 1 required keyword-only argument: 'b'
>>> f(1,2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: f() takes 1 positional argument but 2 were given
>>> f(1,b=2)
>>>
>>> def f(x : int, y : int) -> int:
... return x + y
...
>>> f(2, 3)
5
>>> f('hoge', 'fuga') # エラーにはならない
'hogefuga'
>>> def f():
... global a
... a = 1
...
>>> a # ここではaは未定義
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'a' is not defined
>>> f() # fの呼び出しによりグローバル変数aが定義される
>>> a
1
>>> def make_counter():
... count = 0
...
... def counter():
... nonlocal count
... count += 1
... return count
...
... return counter
...
>>> c = make_counter()
>>> c(), c(), c()
(1, 2, 3)
>>> def greet(before, after):
... def decorator(func):
... def wrapper(*args, **kwargs):
... print(before)
... func(*args, **kwargs)
... print(after)
... return wrapper
... return decorator
...
>>> @greet('Hi.', 'Bye.')
... def introduce(name):
... print('I am ' + name + '.')
...
>>> introduce('yubessy')
Hi.
I am yubessy.
Bye.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment