Reputation: 2825
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.
Upvotes: 0
Views: 1011
Reputation: 37509
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)
Upvotes: 1
Reputation: 3873
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
Upvotes: 1
Reputation: 11807
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.
Upvotes: 1