flask optional argument in request.args - python-3.x

I am building a small API. For now I am having this workaround solution for optional arguments that need to be send to function later.
if 'A' in request.args:
A = request.args['A']
else:
A = 0
but I feel like that there must be something precise. This seems a bit unprofessional. Something like when I work argparse
parser.add_argument('--A', type=int, required=False')
Please, is it possible to shorten the first section a bit and use some of their functions for it? Thanks

You can use get method something like:
a = request.args.get('A', None)
It puts 'A' value if it exists in args or just None if it doesn't. You can also replace None with any other data like 0 or 'nothing' or everything else.

Related

How can I accept only some strings in Python function?

I want to make it like this:
>>> myfunc("strawberry")
ok
# myfunc only works with strawberry
I know that most people will answer with:
def myfunc(something):
if something == "strawberry":
print("ok")
But I want to do all this in the parameter setting.
Like, kind of like this:
def myfunc(something: OnlyThese["strawberry", "cake"]:
print("ok")
Although the code above is very incorrect, I want to see if Python already has a feature like this.
Don't believe there is a way to do what you are wanting to do without writing code in the function body.
I found answers to a similar question at
enforce arguments to a specific list of values

how can I passed my test when the programm takes no arguments and I tried to use #staticmethod before my function and nothing happend

I'm a python beginner and I tried to pass my code in the pytest and nothing happens.
And appear the TypeError: read_products() takes 0 positional arguments but 1 was given. But my read_products function doesn't take any parameters. I tried to use #staticmethod before the function and includes "self" as a parameter and nothing happened. So please, Help me! The first link is my program and the second one is my test program.
https://codeshare.io/zy7nd4
https://codeshare.io/wnqKdx
In your main file you have your function defined with zero parameters (which is what you want, if I understand correctly)
def read_products():
However, when you call it from the test file, you call it with the argument "products.csv"
def test_read_products():
...
products_dict = read_products("products.csv")
...
Maybe what you want is to call it like this
products_dict = read_products()
Also, if possible please post your code in your question instead of an external site, thanks

Enter new variable as argument

I want to create a function that takes some chain of characters as an argument, and uses it as a str object.
def useless_function(argument) :
print(argument)
useless_function(banana)
--> NameError: name 'banana' is not defined
So this is what I did : I created a decorator that turns whatever I enter as argument into a str my function can print.
def decorator(f) :
def wrapper(arg_f) :
str_arg = str(arg)
f(str_arg)
return wrapper
So now I can decorate useless_function with my decorator, and useless_function(banana) will print 'banana'. And it will work with whatever it enter as an argument of useless_function.
My question is : is there a more elegant way or a simpler and faster way to do this automatic transformation into a string that can be used as an argument ?
Can you please elaborate because I don't understand what it is that you are looking for or saying.
If you mean: inside a function can you do input("variable")? Then the answer is yes. It is just essentially raw_input() from python2. The input from your keyboard will always be a str if I am not mistaken.
Update after edited post:
It is still not any more clear what you are trying to do.
At the end of the function, you do return * but I assume you know this.
I am really confused, but have you considered just doing str(argument)? As in takes_argument(str(argument))
2nd Update after 2nd edit:
I think I finally understand what you are trying to do, but I might be wrong.
Now, the problem is that def useless_function(argument) : will expect argument to be defined as a variable with some value(s). I am not aware of any other way than actually putting "argument" to tell python that what you are inserting is a string of characters rather than trying to reference some variable and its value. It is the same case as with print('something'), if I were to put print(something), python would try to look up the variable called something which you haven't defined.
Hope that makes sense.

Builder with optional source

I want to make a Builder with one or more optional sources.
I tried this:
env.Append(BUILDERS = {'my_builder': Builder(action = Action(do_something))})
def do_something(target, source, env):
if source[1]:
do_optional_stuff(source[1])
do_other_stuff(target, source[0])
...
env.my_builder(target.txt, [source1, None]) # Fails
env.my_builder(target.txt, [source2, source3]) # Okay
The trouble is, I get 'NoneType' object has no attribute 'get_ninfo' when I pass in None, because scons is expecting Node arguments, and None isn't acceptable.
Is there anything I can do?
Edit:
As noted in the answer below, it's possible to solve this for the simple case of one optional argument, by varying the length of source list. This doesn't work for making arbitrary arguments optional, so I'd still be interested in a way to do that.
Instead of adding a bogus element, check the length of the source list (or better yet, iterate over the list starting after the first element):
def do_something(target, source, env):
if len(source) > 1:
do_optional_stuff(source[1])
# or:
# for opt_src in source[1:]:
# do_optional_stuff(opt_src)
do_main_stuff(target, source[0])
env.Append(BUILDERS = {'my_builder': Builder(action = Action(do_something))})
env.my_builder('target-2.txt', ['foo.txt'])
env.my_builder('target-1.txt', ['foo.txt', 'bar.txt'])
One issue with this approach is that you need to ensure that your sources are listed in the right order. Depending on the details of what you're doing, you might be able to filter the source list by matching file names or extensions. After all, this is Python code, you have the full power of the language at your disposal.

Can Python use a functions default parameter when an inline if fails when calling it?

If I have a variable that has a value I don't want passed to a function, is it possible to do it without several ifs, especially if there are several variables that may or may not need to be passed in?
Take the following:
def test(param=""):
...do stuff
x = None
test(x if x else ?)
^
What can i put here so it
defaults to the default in
the function definition?
If this isn't possible, is there a quick way of doing this when there are multiple variables that may or may not need to be passed in rather than a lot of ifs?
Basic answer:
if(x): test(x)
else: test()
With *args you can pass in as many variables as you want but I don't think that will help you. The best I can think of is multiple ifs (Python doesn't allow overloading unfortunately).
That would look like:
if x:
if y:
if z: test(x,y,z)
else: test(x,y)
else: test(x)
else: test()
The reason you can't call test(x,z) or test(y) for example is because your method assumes a certain order in the signature so you wouldn't be able to specify which arg you are passing in at function call. In Java you could do it with overloading and different argument types, but not here afaik.

Resources