TIL

Today I Learned. 知ったこと、学んだことを書いていく

nonlocal ネストした関数から変数にアクセスする - Python

ネストした関数で、上で定義された変数を使うにはnonlocalキーワードを使う

def main():
    a = 1

    def child():
        nonlocal a
        a += 1
        print(a)

    print(a)
    child()
    print(a)

main()

出力結果

1
2
2

ネストした関数から、アクセスできた!!

これは、メモ化のための実装方法らしい。クロージャというやつ
メモ化ってどっかで聞いたことある。
たしか、同じ引数だったら、前回の結果をそのまま返すやつだっけ

クロージャについてはこんどちゃんとやる。こんど。うん。

参考文献

os.path.expanduser関数 - Python

カレントユーザのホームディレクトリのパスを取得することができる

>>> os.path.expanduser('~/src/python/')
'/Users/tamago324/src/python/'

使えるときあるのかな?

参考文献

【IFNULL関数】 AがNULLだったら、B。AがNULLじゃなかったら、Aを返す関数 - MySQL

便利なのを知ったからメモ

もし、第1パラメータがNULLだったら、第2パラメータを返し、
第1パラメータがNULLじゃなかったら、第2パラメータを返してくれる便利なやつ

第1パラメータがNULLではない時

SELECT IFNULL('AAA', 'BBB') FROM DUAL

結果

AAA

第1パラメータが返ってくる

第1パラメータがNULLの時

SELECT IFNULL(NULL, 'BBB') FROM DUAL

結果

BBB

第2パラメータが返ってくる

Pythonでのorみたいな?

>>> 'hoge' or 'fuga'
'hoge'

>>> None or 'fuga'
'fuga'

参考文献

keybindingに渡されるeventという引数は何者!? - Python

keybindingのメソッドに渡されるeventという引数は何者?

prompt_toolkit.key_binding.key_processor.KeyPressEventというやつ

https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/key_binding/key_processor.py#L412

  • data
  • key_processor
  • app: The current Application object.
  • current_buffer: The current buffer.
  • arg
  • arg_present
  • append_to_arg_count
  • cli
@kb.add('a')
def _(event):
    event.app.xxxxx

みたいにevent.appしておけばどうにかなる説

Application オブジェクトに全部格納してるから、それ見ればなんとかなるしょみたいな

ちょっと脱線

Applicaiton.current_bufferlayout.current_bufferらしい?

https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/application/application.py#L306

    @property
    def current_buffer(self):
        """
        The currently focused :class:`~.Buffer`.

        (This returns a dummy :class:`.Buffer` when none of the actual buffers
        has the focus. In this case, it's really not practical to check for
        `None` values or catch exceptions every time.)
        """
        return self.layout.current_buffer or Buffer(name='dummy-buffer')  # Dummy buffer.

あれか、起動する時にapp = Application(layout=xxxx)ってやったときのやつが取得できるってことか!!

また、特定のウィンドウにフォーカスがあうかどうかとかはhas_focusを使う

カーソルがある行のインデックス番号を取得 - Python

python-prompt-toolkitでカーソル行のインデックス番号を取得したいとき

prompt_toolkit.document.Document.cursor_position_row

カーソルがある行のインデックス番号が取得できる

0から数える

from prompt_toolkit.application import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import Window
from prompt_toolkit.layout.controls import BufferControl
from prompt_toolkit.layout.layout import Layout
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document

from logging import getLogger, config
config.fileConfig("logger.conf")
logger = getLogger(__name__)


text = '\n'.join([str(i) for i in range(100)])

body = Window(BufferControl(Buffer(document=Document(text))), cursorline=True)

# キーバインディング
kb = KeyBindings()


@kb.add('q')
def _(event):
    event.app.exit()


@kb.add('o')
def _(event):
    # ここ!!!!
    logger.debug(event.current_buffer.document.cursor_position_row)


app = Application(
        layout=Layout(body),
        key_bindings=kb,
        full_screen=True)

app.run()

Enterを押すと、インデックス番号が取得できる

logger.confは以下のようになっている

[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=fileHandler

[handler_fileHandler]
class=FileHandler
level=DEBUG
; ハンドラで使用するフォーマッタを指定
formatter=simpleFormatter
; FileHandlerのコンストラクタへの引数
args=("log.log", "a+")

[formatter_simpleFormatter]
format=%(asctime)s:%(levelname)s %(message)s
; 時間の表示形式を設定
datefmt=%Y-%m-%d %H:%M:%S