Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@homecoder
Created February 23, 2018 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save homecoder/1fa460eb865dd46488051c32a68a671f to your computer and use it in GitHub Desktop.
Save homecoder/1fa460eb865dd46488051c32a68a671f to your computer and use it in GitHub Desktop.
Python 'switch' statement.
# -*- coding: utf-8 -*-
"""
Copyright 2018 Michael Ruggiero - This code is released under the MIT License.
Personal Request: If you find this useful, can you reach out to me on GitHub (create an issue, just email me michael AT ruggiero.co) I'd really love to see/hear how it was used.
Of course, it's MIT so you don't have to; just leave the copyright in-tact as per the license.
LICENSE:
Copyright 2018 Michael Ruggiero
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class Switch (object):
"""
FULL DISCLOSURE: This is *NOT* The Pythonic way of doing things. I was asked not too long ago by a friend if you "could" do a similar implementation of "switch" in Python.
I am going to challenge myself to get an even closer match to how c/php etc work, but for now - this will do.
If anyone see's this, I am definitely going to repost this later on with some updates; specifically where this might actually make sense.
In any capacity, I've yet to see
"""
def __init__(self, var):
self.var = var
def __enter__(self):
return self
def __exit__(self, *args):
return
def __next__(self):
return self.next()
def __getattr__(self, item):
"""
When going through this, if we are trying to save 2-3 keypresses why not save a few more.
"""
def wrapper(*args, **kwargs):
return getattr(str(type(self.var)).split("'")[1], item)(*args, **kwargs)
return wrapper
def __repr__(self):
"""
>>> s = Switch('hello')
>>> print(s)
hello
"""
return self.var
def case(self, var, val=None, obj=False, dict=False):
if isinstance(var, (list, tuple)):
return self.var in var
elif isinstance(var, str):
return var == self.var
elif isinstance(var, object) and obj:
if hasattr(var, self.var):
return getattr(self.var, str(var)) == val
elif isinstance(var, dict) and dict:
if var in self.var:
return self.var[var] == val
def true(self, var):
"""
Since we are being usless, lets try to shorten a Boolean expression
"""
return self.var == var
def false(self, var):
"""
Since we are being usless, lets try to shorten a Boolean expression
"""
return not self.true(var)
def default(self):
"""
You could always use if / elif / else - but hey, why not.
"""
return True
## Usage
answer = "special"
with Switch(answer) as s:
"""
This is fairly useless but pretty to write; Since you can't use break/continue outside of a loop,
You can basically either use a while True: then make sure you have a break (or infinite loop you go) OR
just use elif .. seriously. This isn't even useful as is.
"""
if s.case('python'):
print('Lovely word, but not going to display')
if s.case('answer'):
print('Not quite that imaginitive')
if s.case('special'):
print('This is exactly what I wanted to hear!')
if s.startswith('s'):
print('This will also show up.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment