Python IniFile Read and Write

前々回 Python の True, False は整数と書いたけど
そういえば isinstance() は?

bool is instance of int in Python – Peterbe.com (Peter Bengtsson on Python, Zope, Kung Fu, London and photos)

やっぱりそうなるか。
他にオブジェクトのタイプを正確に調べるには…

How to compare type of an object in Python? – Stack Overflow

こんなに色々タイプ比較方法があったんだ、めもめも。
でも速度はどうなるんだろう?

import time

t = 100000

s0 = time.time()
for i in range(t):
    isinstance(i, int)
print time.time() - s0

s1 = time.time()
for i in range(t):
    type(i) is int
print time.time() - s1

s2 = time.time()
for i in range(t):
    "%d" % i
print time.time() - s2

結果

0.0666399002075
0.0661001205444
0.157742977142

変わらないや、一応試した文字列変換可能かどうかでは遅すぎるかやはり。

設定読み書きクラスを自作する

私が以前自分で書いたコレもサル丸出しだなと。
とにかく type() がいいみたいなので現行版をベースに作りかえてみる。

とはいえもはや SeeMe で使っているのは原型を留めていないのであるが…
ついでにアトリビュートには直接アクセスできないようにとか % 演算子に変更とか…

#!/usr/bin/env python
#-*- coding:utf-8 -*-

ERROR_READ = 'Configuration file READ ERROR\n[%s]\n%s=\nvalue is not %s'
ERROR_WRITE = 'Configuration file WRITE ERROR\n(%s, %s) value is not %s'
ERROR_HEADER = 'Configuration file header value is not str'

import os

class InifileBase():
    """
        This class is Inheritance Base
    """
    def __init__(self, filename):
        """
            Attribute is the file name only
        """
        self._filename = filename

    def _get_value(self, section, key):
        """
            This Methods is Inheritance Base
        """
        return None

    def read_int(self, section, key, default):
        """
            @param default: int.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        try:
            return int(result)
        except:
            raise ValueError, ERROR_READ % (section, key, "int")
    
    def read_float(self, section, key, default):
        """
            @param default: float.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        try:
            return float(result)
        except:
            raise ValueError, ERROR_READ % (section, key, "float")
    
    def read_bool(self, section, key, default):
        """
            @param default: bool.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        if result == "1" or result == "-1":
            return True
        elif result == "0":
            return False
        else:
            raise ValueError, ERROR_READ % (section, key, "bool")
    
    def read_str(self, section, key, default):
        """
            @param default: str.
        """
        result = self._get_value(section, key)
        if result == None:
            return default
        return result


class InifileReader(InifileBase):
    """
        This class is read-only
        ini files to load faster
    """
    def __init__(self, filename):
        """
            @param filename: the full path name.
        """
        InifileBase.__init__(self, filename)

    def _get_value(self, section, key):
        """
            Read using the file stream
        """
        if os.path.exists(self._filename):
            section_in = False
            f = open(self._filename)
            try:
                for linenn in f:
                    line = linenn.strip()
                    if line == "":
                        continue
                    if section_in:
                        if "=" in line:
                            pos = line.index("=")
                            if key == line[:pos]:
                                return line[pos+1:]
                        if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                            return None
                    if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                        if section == line[1:-1]:
                            section_in = True
            finally:
                f.close()
        return None


class Inifile(InifileBase):
    """
        ini file to read and write class.
    """
    def __init__(self, filename):
        """
            Loading degradation inifile
            @param filename: the full path name.
        """
        InifileBase.__init__(self, filename)
        self._header = ""
        self._ini = []
        if os.path.exists(filename):
            f = open(filename)
            x = f.read()
            f.close()
            lines = x.split("\n")
            section = ""
            for line in lines:
                if line == "":
                    continue
                if len(line) > 2 and line[0] =="[" and line[-1] == "]":
                    section = line[1:-1]
                elif section == "":
                    pass # Nothing
                elif "=" in line:
                    pos = line.index("=")
                    self._add(section, line[:pos], line[pos+1:])
    
    def _add(self, section, key, value):
        """
            Add to contents.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        dic2[key] = value
                        return
                dic1[section].append({key: value})
                return
        self._ini.append({section: [{key: value}]})
    
    def _get_value(self, section, key):
        """
            Get to contents.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        return dic2[key]
        return None
    
    def save(self):
        """
            Save the contents.
        """
        s = ""
        if self._header:
            s += self._header
        for dic1 in self._ini:
            for section in dic1.keys():
                s += "[%s]\n" % section
                for dic2 in dic1[section]:
                    for key in dic2.keys():
                        s += "%s=%s\n" % (key, dic2[key])
                s += "\n"
        if s != "":
            f = open(self._filename, "w")
            f.write(s)
            f.close()

    def add_header(self, header):
        """
            @param headre: str.
        """
        if type(header) is str:
            self._header = header
        else:
            raise ValueError, ERROR_HEADER

    def section_exists(self, section):
        """
            Check existence of section.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                return True
        return False
    
    def erase_section(self, section):
        """
            Remove the specified section.
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                dic1.pop(section)
                return True
        return False

    def erase_key(self, section, key):
        """
            Erase Key
        """
        for dic1 in self._ini:
            if section in dic1.keys():
                for dic2 in dic1[section]:
                    if key in dic2.keys():
                        dic2.pop(key)
                        return True
        return False

    def write_int(self, section, key, value):
        """
            @param value: int.
        """
        if type(value) is int:
            self._add(section, key, str(value))
        else:
            raise ValueError, ERROR_WRITE % (section, key, "int")
    
    def write_float(self, section, key, value):
        """
            @param value: float.
        """
        if type(value) is float:
            self._add(section, key, str(value))
        else:
            raise ValueError, ERROR_WRITE % (section, key, "float")
    
    def write_bool(self, section, key, value):
        """
            @param value: bool.
        """
        if type(value) is bool:
            if value:
                self._add(section, key, "1")
            else:
                self._add(section, key, "0")
        else:
            raise ValueError, ERROR_WRITE % (section, key, "bool")
    
    def write_str(self, section, key, value):
        """
            @param value: str.
        """
        if type(value) is str:
            self._add(section, key, value)
        else:
            raise ValueError, ERROR_WRITE % (section, key, "str")

継承使っているし、こうなると初心者は見ても意味解らないかも。
Y901x と SeeMe に使うのはこれでいいとして、覚書ページはどうするか…
てかあそこに書いた方法では今では動画再生できなくなったと解っているんだが。