12
13

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でconstant

Last updated at Posted at 2012-03-16

Pythonで、CやC++のconst定数のような変更不可能なオブジェクトを作る方法はないでしょうか。
Python CookBookを見てconstを導入したところ、再代入は防げているのですが、辞書自体が操作可能なので期待している動きをしません。

オブジェクトの状態自体も変更不可にしたいです。
汎用的で良い方法があれば教えてください。

Cookbookに載っていたコード

qiita.rb
puts 'The best way to log and share programmers knowledge.'
const.py
## -*- coding: utf-8 -*-

class _const(object):
    class ConstError(TypeError):pass
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError("Can't rebind const(%s)" % name)
        self.__dict__[name] = value
        def __delattr__(self, name):
            if name in self.__dict__:
                raise self.ConstError("Can't unbind const(%s)" % name)
            raise NameError(name)

import sys
sys.modules[__name__] = _const()

テストプログラム

const_test.py
# -*- coding: utf-8 -*-
import const

# 最初の代入はOK
const.dic = {'a':'b'}

# これはエラー 
# const.dic = {'c':'d'}

# 追加出来る
const.dic['c'] = 'd'

# 削除できる
del const.dic['a']

print const.dic
12
13
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
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?