1# 2# Gramps - a GTK+/GNOME based genealogy program 3# 4# Copyright (C) 2000-2007 Donald N. Allingham 5# Copyright (C) 2009 Gary Burton 6# Copyright (C) 2011 Tim G L Lyons 7# 8# This program is free software; you can redistribute it and/or modify 9# it under the terms of the GNU General Public License as published by 10# the Free Software Foundation; either version 2 of the License, or 11# (at your option) any later version. 12# 13# This program is distributed in the hope that it will be useful, 14# but WITHOUT ANY WARRANTY; without even the implied warranty of 15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16# GNU General Public License for more details. 17# 18# You should have received a copy of the GNU General Public License 19# along with this program; if not, write to the Free Software 20# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21# 22 23""" 24Utility functions to cast types 25""" 26 27#------------------------------------------------------------------------- 28# 29# Python modules 30# 31#------------------------------------------------------------------------- 32import os 33import sys 34import logging 35LOG = logging.getLogger(".") 36 37#------------------------------------------------------------------------- 38# 39# Gramps modules 40# 41#------------------------------------------------------------------------- 42from ..const import GRAMPS_LOCALE as glocale 43_ = glocale.translation.gettext 44 45def cast_to_bool(val): 46 return val in ['True', 'true', _('True'), _('true'), '1'] # 3139 47 48def get_type_converter(val): 49 """ 50 Return function that converts strings into the type of val. 51 """ 52 val_type = type(val) 53 if isinstance(val, str): 54 return str 55 elif val_type == int: 56 return int 57 elif val_type == float: 58 return float 59 elif val_type == bool: 60 return cast_to_bool 61 elif val_type in (list, tuple): 62 return list 63 64def type_name(val): 65 """ 66 Return the name the type of val. 67 68 Only numbers and strings are supported. 69 The rest becomes strings (unicode). 70 """ 71 val_type = type(val) 72 if val_type == int: 73 return 'int' 74 elif val_type == float: 75 return 'float' 76 elif val_type == bool: 77 return 'bool' 78 elif isinstance(val, str): 79 return 'unicode' 80 return 'unicode' 81 82def get_type_converter_by_name(val_str): 83 """ 84 Return function that converts strings into the type given by val_str. 85 86 Only numbers and strings are supported. 87 The rest becomes strings (unicode). 88 """ 89 if val_str == 'int': 90 return int 91 elif val_str == 'float': 92 return float 93 elif val_str == 'bool': 94 return cast_to_bool 95 elif val_str in ('str', 'unicode'): 96 return str 97 return str 98