简体   繁体   中英

How to force a Python's function to accept a certain input?

Regardless of whether it's a good idea or not, I wanted to know whether it would be possible to force a method to accept a certain input, for example a character without quotes ("!"). Exempli gratia:

def special_print(text):
    """Print <text> unless ! (no quotes!) is passed as argument."""
    if text == !:
        print("Easter egg!")
    else:
        print(text)


special_print("Hello, World"!)
>>> Hello, World!

special_print("!")
>>> !

special_print(!)
>>> Easter egg!

Would that be possible? Just curious.

This isn't possible unless you make your own build of the Python source.

The only exception is for ... , which equates to an Ellipsis object in Python 3 (not Python 2). So you could do:

def special_print(text):
    """Print <text> unless ... (no quotes!) is passed as argument."""
    if text == ...:
        print("Easter egg!")
    else:
        print(text)

... is designed to be used in slices, but as of Python 3 you can use it anywhere.

No this is not possible in the way you described, but I guess that you want to use that kind of syntax in the interactive shell, otherwise I can't even imagine how this can be useful. In this case writing your own shell with cmd module will be the way to go. For example:

import cmd

class SpecialPrint(cmd.Cmd):

    def do_print(self, line):
        print line

    def do_exit(self, line):
        return True

if __name__ == '__main__':
    SpecialPrint().cmdloop()

Running of this code will spawn a shell that works as follows:

(Cmd) print !
!
(Cmd) print anything you want
anything you want
(Cmd) exit

You're kind of asking a different question in a roundabout way. Python is dynamically typed, so a function will accept any type. You can do something similar to what you want using other types, possibly using Sentinel objects.

Sentinel = object()

def special_print(text):
    if text is Sentinel:
        print("Easter egg!")
    else:
        print(text)

special_print(Sentinel)

You can't use a ! character because that isn't a valid variable name. You don't have to use Sentinel objects either, just use non-string variables

def special_print(text):
    if isinstance(text, int):
        print("Easter egg!")
    else:
        print(text)

special_print(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM