2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

回りくどすぎるPythonコードを書く

Posted at

初めに

インタプリタ言語は、実行速度という最大の弱点を持つものの、
コードはとても簡潔に書けて読みやすい(ことが多い)。

そこで、僕が思ったのは

あえて長くコードを書くことはできるのか?

ということ。
インタプリタの恩恵を実感するためにも、あえて長くコードを書くことにした。

対象

  • C言語がちょっとはわかる人 (#includeとint mainぐらい)

今回作るもの

プログラミングと言ったら誰もが最初は通るであろう
Hello world!\n」を出力するプログラムを書くことにした。

一応、通常のPythonでこれを書いてみると、

print("Hello world!")

となる。Pythonは標準でprintという関数が内蔵されており、
簡単に文字列が出力できる。

完成品

そして、できたのが以下のコード。

import sys

def main():
    with sys.stdout as text:
        text.write("Hello world!\n")
        
    sys.exit(0)

if __name__ == "__main__":
    main()

なんと全部で10行。空行を除いても7行。
あまり見慣れないコードがあったりもするので、
初心者向けに解説することにする。

解説

import sys

これはそのままの意味で、sysというモジュールをインポートする。
#include <stdio.h>と似たような意味である。

def main()

これはC言語のint main () {}部に等しい。

Pythonはmain関数を自動で実行してくれないので、

if __name__ == "__main__":
    main()    

が必要。

with sys.stdout as text: ...

これが肝心な部分。実はsysモジュールには、
stdout1というものがあり、これを使うとprint関数を
使わずに回りくどく文字列を出力することができるのだ!
さらに、標準で改行も付け加えられないので、\nを自分で書く必要がある。

sys.exit(0)

Pythonはプログラム終了時に標準でコード0で終了してくれるが
それを手動で行なっている。本当に意味がない。

C言語で書いてみると?

#include <stdio.h>

int main() {
    puts("Hello world!");
    return 0;
}

全部で6行。なんとあのCを超える行数になっていることがわかった。

結果

- print("Hello world!")
+ import sys
+ 
+ def main():
+     with sys.stdout as text:
+         text.write("Hello world!\n")
+         
+     sys.exit(0)
+ 
+ if __name__ == "__main__":
+     main()
  • Pythonは工夫次第で回りくどくできる。
  • C言語も超える。
  • 普通に書けば良くね?

最後まで読んでいただきありがとうございました!
回りくどいコードの改善案、もっと回りくどくする方法があったら
コメントで教えてください!

  1. ちょっとファイル操作に似てる。

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?