using decorator arguments for switching
At the flaks library, we can use decorator like switch case. (Did I understand well?)
app.route('')
So...I would like to make some switch statement with decorators and arguments,
like:
@color('pink')
def _pink_power(self):
print("wow")
@color('blue')
@color('red')
def _powerpower(self):
print("god!!!!")
def input(color):
I don't know what to do in here..
if color is pink, print wow!
I was struggling to figure out this quite a long time, but I couldn't make it. Is it impossible do you think?
python decorator
add a comment |
At the flaks library, we can use decorator like switch case. (Did I understand well?)
app.route('')
So...I would like to make some switch statement with decorators and arguments,
like:
@color('pink')
def _pink_power(self):
print("wow")
@color('blue')
@color('red')
def _powerpower(self):
print("god!!!!")
def input(color):
I don't know what to do in here..
if color is pink, print wow!
I was struggling to figure out this quite a long time, but I couldn't make it. Is it impossible do you think?
python decorator
add a comment |
At the flaks library, we can use decorator like switch case. (Did I understand well?)
app.route('')
So...I would like to make some switch statement with decorators and arguments,
like:
@color('pink')
def _pink_power(self):
print("wow")
@color('blue')
@color('red')
def _powerpower(self):
print("god!!!!")
def input(color):
I don't know what to do in here..
if color is pink, print wow!
I was struggling to figure out this quite a long time, but I couldn't make it. Is it impossible do you think?
python decorator
At the flaks library, we can use decorator like switch case. (Did I understand well?)
app.route('')
So...I would like to make some switch statement with decorators and arguments,
like:
@color('pink')
def _pink_power(self):
print("wow")
@color('blue')
@color('red')
def _powerpower(self):
print("god!!!!")
def input(color):
I don't know what to do in here..
if color is pink, print wow!
I was struggling to figure out this quite a long time, but I couldn't make it. Is it impossible do you think?
python decorator
python decorator
edited Nov 23 '18 at 11:11
martineau
70.1k1092186
70.1k1092186
asked Nov 23 '18 at 10:38
hahahaha
155
155
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Here's a relatively simple way to do it (although I recommend that you change the name of the input
function at the end because it conflicts with a built-in of the same name):
class color:
_func_map = {}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map[case]()
@color('pink')
def _pink_power():
print("wow")
@color('blue')
@color('red')
def _powerpower():
print("god!!!!")
def input(colorname):
color.switch(colorname)
input('pink') # -> wow
input('blue') # -> god!!!!
input('red') # -> god!!!!
An Enhancement
You could support having a default case like C/C++'s switch
statements support that will be used when there's no matching colorname
:
class color:
DEFAULT = '_DEFAULT'
def _default(): raise ValueError('Unknown color!')
_func_map = {DEFAULT: _default}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map.get(case, cls._func_map[cls.DEFAULT])()
The _default()
method added to the class raises an exception when it's invoked:
input('lavender') # -> ValueError: Unknown color!
However you can override that by defining your own:
@color(color.DEFAULT) # Define custom color default.
def my_default():
print("loser!")
input('lavender') # -> loser!
add a comment |
You...could do this, but I'm not sure it's a great idea to.
import contextlib
class Colors(object):
def __init__(self):
self.__colors = dict()
def register(self, colorname):
def wrapper(f):
@contextlib.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
self.__colors[colorname] = wrapper
return wrapper
def __getitem__(self, item):
return self.__colors[item]
colors = Colors()
@colors.register("pink")
def _pink_power():
print("wow")
@colors.register("blue")
@colors.register("red")
def _powerpurple():
print("god!!!!!")
def input(colorname):
colors[colorname]()
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445074%2fusing-decorator-arguments-for-switching%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here's a relatively simple way to do it (although I recommend that you change the name of the input
function at the end because it conflicts with a built-in of the same name):
class color:
_func_map = {}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map[case]()
@color('pink')
def _pink_power():
print("wow")
@color('blue')
@color('red')
def _powerpower():
print("god!!!!")
def input(colorname):
color.switch(colorname)
input('pink') # -> wow
input('blue') # -> god!!!!
input('red') # -> god!!!!
An Enhancement
You could support having a default case like C/C++'s switch
statements support that will be used when there's no matching colorname
:
class color:
DEFAULT = '_DEFAULT'
def _default(): raise ValueError('Unknown color!')
_func_map = {DEFAULT: _default}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map.get(case, cls._func_map[cls.DEFAULT])()
The _default()
method added to the class raises an exception when it's invoked:
input('lavender') # -> ValueError: Unknown color!
However you can override that by defining your own:
@color(color.DEFAULT) # Define custom color default.
def my_default():
print("loser!")
input('lavender') # -> loser!
add a comment |
Here's a relatively simple way to do it (although I recommend that you change the name of the input
function at the end because it conflicts with a built-in of the same name):
class color:
_func_map = {}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map[case]()
@color('pink')
def _pink_power():
print("wow")
@color('blue')
@color('red')
def _powerpower():
print("god!!!!")
def input(colorname):
color.switch(colorname)
input('pink') # -> wow
input('blue') # -> god!!!!
input('red') # -> god!!!!
An Enhancement
You could support having a default case like C/C++'s switch
statements support that will be used when there's no matching colorname
:
class color:
DEFAULT = '_DEFAULT'
def _default(): raise ValueError('Unknown color!')
_func_map = {DEFAULT: _default}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map.get(case, cls._func_map[cls.DEFAULT])()
The _default()
method added to the class raises an exception when it's invoked:
input('lavender') # -> ValueError: Unknown color!
However you can override that by defining your own:
@color(color.DEFAULT) # Define custom color default.
def my_default():
print("loser!")
input('lavender') # -> loser!
add a comment |
Here's a relatively simple way to do it (although I recommend that you change the name of the input
function at the end because it conflicts with a built-in of the same name):
class color:
_func_map = {}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map[case]()
@color('pink')
def _pink_power():
print("wow")
@color('blue')
@color('red')
def _powerpower():
print("god!!!!")
def input(colorname):
color.switch(colorname)
input('pink') # -> wow
input('blue') # -> god!!!!
input('red') # -> god!!!!
An Enhancement
You could support having a default case like C/C++'s switch
statements support that will be used when there's no matching colorname
:
class color:
DEFAULT = '_DEFAULT'
def _default(): raise ValueError('Unknown color!')
_func_map = {DEFAULT: _default}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map.get(case, cls._func_map[cls.DEFAULT])()
The _default()
method added to the class raises an exception when it's invoked:
input('lavender') # -> ValueError: Unknown color!
However you can override that by defining your own:
@color(color.DEFAULT) # Define custom color default.
def my_default():
print("loser!")
input('lavender') # -> loser!
Here's a relatively simple way to do it (although I recommend that you change the name of the input
function at the end because it conflicts with a built-in of the same name):
class color:
_func_map = {}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map[case]()
@color('pink')
def _pink_power():
print("wow")
@color('blue')
@color('red')
def _powerpower():
print("god!!!!")
def input(colorname):
color.switch(colorname)
input('pink') # -> wow
input('blue') # -> god!!!!
input('red') # -> god!!!!
An Enhancement
You could support having a default case like C/C++'s switch
statements support that will be used when there's no matching colorname
:
class color:
DEFAULT = '_DEFAULT'
def _default(): raise ValueError('Unknown color!')
_func_map = {DEFAULT: _default}
def __init__(self, case):
self.case = case
def __call__(self, f):
self._func_map[self.case] = f
return f
@classmethod
def switch(cls, case):
cls._func_map.get(case, cls._func_map[cls.DEFAULT])()
The _default()
method added to the class raises an exception when it's invoked:
input('lavender') # -> ValueError: Unknown color!
However you can override that by defining your own:
@color(color.DEFAULT) # Define custom color default.
def my_default():
print("loser!")
input('lavender') # -> loser!
edited Nov 26 '18 at 6:22
answered Nov 23 '18 at 12:24
martineaumartineau
70.1k1092186
70.1k1092186
add a comment |
add a comment |
You...could do this, but I'm not sure it's a great idea to.
import contextlib
class Colors(object):
def __init__(self):
self.__colors = dict()
def register(self, colorname):
def wrapper(f):
@contextlib.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
self.__colors[colorname] = wrapper
return wrapper
def __getitem__(self, item):
return self.__colors[item]
colors = Colors()
@colors.register("pink")
def _pink_power():
print("wow")
@colors.register("blue")
@colors.register("red")
def _powerpurple():
print("god!!!!!")
def input(colorname):
colors[colorname]()
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
add a comment |
You...could do this, but I'm not sure it's a great idea to.
import contextlib
class Colors(object):
def __init__(self):
self.__colors = dict()
def register(self, colorname):
def wrapper(f):
@contextlib.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
self.__colors[colorname] = wrapper
return wrapper
def __getitem__(self, item):
return self.__colors[item]
colors = Colors()
@colors.register("pink")
def _pink_power():
print("wow")
@colors.register("blue")
@colors.register("red")
def _powerpurple():
print("god!!!!!")
def input(colorname):
colors[colorname]()
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
add a comment |
You...could do this, but I'm not sure it's a great idea to.
import contextlib
class Colors(object):
def __init__(self):
self.__colors = dict()
def register(self, colorname):
def wrapper(f):
@contextlib.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
self.__colors[colorname] = wrapper
return wrapper
def __getitem__(self, item):
return self.__colors[item]
colors = Colors()
@colors.register("pink")
def _pink_power():
print("wow")
@colors.register("blue")
@colors.register("red")
def _powerpurple():
print("god!!!!!")
def input(colorname):
colors[colorname]()
You...could do this, but I'm not sure it's a great idea to.
import contextlib
class Colors(object):
def __init__(self):
self.__colors = dict()
def register(self, colorname):
def wrapper(f):
@contextlib.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
self.__colors[colorname] = wrapper
return wrapper
def __getitem__(self, item):
return self.__colors[item]
colors = Colors()
@colors.register("pink")
def _pink_power():
print("wow")
@colors.register("blue")
@colors.register("red")
def _powerpurple():
print("god!!!!!")
def input(colorname):
colors[colorname]()
answered Nov 23 '18 at 10:55
Adam SmithAdam Smith
35.3k73376
35.3k73376
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
add a comment |
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
Thank u soooo much but why do you think this is a not good idea?
– haha
Nov 23 '18 at 11:09
1
1
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
I don't think the functionality you gain is worth the weird code structure you have to write. You won't remember why you did this in a year, and definitely won't remember how it works.
– Adam Smith
Nov 23 '18 at 11:16
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445074%2fusing-decorator-arguments-for-switching%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown