2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python で名前空間を汚さずにローカルスコープを作る

Posted at

敬虔な Pythonista の皆さんには叱られそうな話題ですが、埋め込み Python 環境で名前空間を汚さずに処理がしたいという状況で、下記のようなコードを使ってローカルスコープを作ってみました。
動作は Python 2.7.4/3.3.1 で確認していますが、大したことはしていませんので他のバージョンでも動くと思います。

localscope.py
DummyClassForLocalScope = "global value"

try:
    class DummyClassForLocalScope:
        # you can write any code here

        raise RuntimeError("Exit from local scope")
except RuntimeError as exception:
    if exception.args != ("Exit from local scope",):
        raise exception

print(DummyClassForLocalScope)

class文でローカルスコープを作り、ローカルスコープの最後で例外を発生させることでクラスの作成をキャンセルしているだけです。

間違っても多用はしたくありませんが、JavaScriptの(function(){...}());的なことがどうしてもしたい場合は、こんな方法もありますよということで。

2
2
3

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?