From f03583993e65a144b6029f11d46075bb35acc0e1 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 23 Apr 2008 11:11:24 +0100 Subject: [PATCH] Try to convert unicode objects to str if they're ascii, rather than asserting they're already str objects. --- pybindgen/cppclass.py | 2 +- pybindgen/module.py | 8 ++++---- pybindgen/utils.py | 19 +++++++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 808dce7..7358cd3 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -909,7 +909,7 @@ public: name -- optional name of the class method as it will appear from Python side """ - assert name is None or isinstance(name, str) + name = utils.ascii(name) if isinstance(method, CppMethod): if name is None: diff --git a/pybindgen/module.py b/pybindgen/module.py index 48391c0..033332a 100644 --- a/pybindgen/module.py +++ b/pybindgen/module.py @@ -93,7 +93,7 @@ class Module(object): include -- the name of the header file to include, including surrounding "" or <>. """ - assert isinstance(include, str) + include = utils.ascii(include) assert include.startswith('"') or include.startswith('<') assert include.endswith('"') or include.endswith('>') if include not in self.includes: @@ -109,7 +109,7 @@ class Module(object): c_function_name_transformer callback, or strip_prefix, will be used to guess the Python name. """ - assert name is None or isinstance(name, str) + name = utils.ascii(name) assert isinstance(wrapper, Function) if name is None: name = self.c_function_name_transformer(wrapper.function_name) @@ -138,7 +138,7 @@ class Module(object): Add a nested module namespace corresponding to a C++ namespace. Returns a Module object that maps to this namespace. """ - assert isinstance(name, str) + name = utils.ascii(name) return Module(name, parent=self, cpp_namespace=name) def add_enum(self, enum): @@ -169,7 +169,7 @@ class Module(object): KeyError >>> module.declare_one_time_definition("bar") """ - assert isinstance(definition_name, str) + definition_name = utils.ascii(definition_name) if definition_name in self.one_time_definitions: raise KeyError self.one_time_definitions[definition_name] = None diff --git a/pybindgen/utils.py b/pybindgen/utils.py index 7f01094..93536f3 100644 --- a/pybindgen/utils.py +++ b/pybindgen/utils.py @@ -109,3 +109,22 @@ def call_with_error_handling(callable, args, kwargs, wrapper, raise else: raise + + +def ascii(value): + """ + ascii(str_or_unicode_or_None) -> str_or_None + + Make sure the value is either str or unicode object, and if it is + unicode convert it to ascii. Also, None is an accepted value, and + returns itself. + """ + if value is None: + return value + elif isinstance(value, str): + return value + elif isinstance(value, unicode): + return value.encode('ascii') + else: + raise TypeError("value must be str or ascii string contained in a unicode object") +