在Python中断言变量类型的正确方法 [英] Proper way to assert type of variable in Python

查看:189
本文介绍了在Python中断言变量类型的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用函数时,我希望确保变量的类型符合预期.怎么做对呢?

In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?

以下是一个伪函数示例,尝试在继续其作用之前执行此操作:

Here is an example fake function trying to do just this before going on with its role:

def my_print(begin, text, end):
    """Print 'text' in UPPER between 'begin' and 'end' in lower

    """
    for i in (begin, text, end):
        assert isinstance(i, str), "Input variables should be strings"
    out = begin.lower() + text.upper() + end.lower()
    print out

def test():
    """Put your test cases here!

    """
    assert my_print("asdf", "fssfpoie", "fsodf")
    assert not my_print("fasdf", 33, "adfas")
    print "All tests passed"

test()

是否主张正确的方法?我应该改用try/except吗?

Is assert the right approach? Should I use try/except instead?

此外,我断言的一组测试似乎无法正常工作:S

Also, my assert set of tests does not seem to work properly :S

感谢pythoneers

Thanks pythoneers

推荐答案

isinstance 如果确实需要,内置的方法是首选的方式,但是更好的方法是记住Python的座右铭:请求宽容比允许更容易"!-)(实际上是Grace Murray Hopper最喜欢的座右铭;-).即:

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

顺便说一句,顺便说一句,该函数可以在Unicode字符串上正常工作-无需任何额外的努力!-)

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

这篇关于在Python中断言变量类型的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆