This question already has answers here:
Why are "pure" functions called "pure"? [closed]
(5 answers)
Closed 6 years ago.
Can pure functions take an argument? For example,
def convert(n):
Thank you in advance
Of course they can have arguments. The only difference is whether they have side effects beyond the input and output parameters. Without input arguments to use as "inspiration", it's difficult for a pure function to do something useful.
Yes they can have arguments. Find some details below:
Pure functions: Functions have some input (their arguments) and return some output
(the result of applying them). The built-in function:
>>> abs(-2)
gives the result:
2
No effects beyond returning a value.
Non-pure functions: In addition to returning a value, applying a non-pure function can generate side effects, which make some change to the state of the interpreter or
computer. A common side effect is to generate additional output beyond the return
value, using the print function.
print(1, 2, 3)
1 2 3
Related
This question already has answers here:
Pythonic way to have a choice of 2-3 options as an argument to a function
(9 answers)
Closed 3 months ago.
I need to force function inputs to take specific values. Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?
def product(product_type = ['apple','banana']):
print(product_type)
But the function requires product_type as single string (product('apple') or product('banana')), and gives error when typed different values.
Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?
Not really.
You can use typing with an Enum or a Literal but that assumes a type checker is actually being run on the codebase in all cases.
Python is otherwise dynamically, it will not normally validate parameters, if you need that you must do it internally. Though you do not need an if: else: block inside the function, you can just use an assertion:
def product(product_type: Literal['apple', 'banana']):
assert product_type in ['apple','banana']
print(product_type)
This way the input will be
actually checked at runtime
documented for IDEs and friends
optionally checked at compile-time
This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 2 years ago.
In Python, there are functions that need parentheses and some that don't, e.g. consider the following example:
a = numpy.arange(10)
print(a.size)
print(a.var())
Why does the size function not need to be written with parentheses, as opposed to the variance function? Is there a general scheme behind this or do you just have to memorize it for every function?
Also, there are functions that are written before the argument (as opposed to the examples above), like
a = numpy.arange(10)
print(np.round_(a))
Why not write a.round_ or a.round_()?
It sounds like you're confused with 3 distinct concepts, which are not specific to python, rather to (object oriented) programming.
attributes are values, characteristics of an object. Like array.shape
methods are functions an object can run, actions it can perform. array.mean()
static methods are functions which are inherent to a class of objects, but don't need an object to be executed like np.round_()
It sounds like you should look into OOP: here is a python primer on methods.
Also, a more pythonic and specific kind of attributes are propertys. They are methods (of an object) which are not called with (). Sounds a bit weird but can be useful; look into it.
arrange returns an ndarray. size isn't a function, it's just an attribute of the ndarray class. Since it's just a value, not a callable, it doesn't take parenthesis.
This question already has answers here:
Why is operator module missing `and` and `or`?
(4 answers)
Closed 4 years ago.
I couldn't find the official glossary of python operators but at least it seems that operator library of python doesn't include and or or keyword. They do have operator.and_, but it's for bitwise and operator(&). What makes me more confused is that they do include is or not keywords as operators.
In short, isn't and(and or) an operator? If it isn't, what is the standard of being an operator in Python? I though I'm pretty familiar with python but this problem confuses me a lot at the moment.
Yes, it's an operator. But it's not like the other operators in the operator module.
and short-circuits (i.e., it evaluates its second argument only if necessary). or is similar. Therefore, neither can be written as a function, because arguments to functions are always fully evaluated before the function is called. In some cases this would make no real difference, but when the second argument contains a function call with side effects (such as I/O), or a lengthy calculation, and's behavior is very different from that of a function call.
You could implement it by passing at least the second argument as a function:
def logical_and(a, b):
if not a:
return a
return b()
Then you could call it as follows:
logical_and(x, lambda: y)
But this is a rather unorthodox function call, and doesn't match the way the other operators work, so I'm not surprised the Python developers didn't include it.
This question already has answers here:
New operators in Python
(4 answers)
Closed 5 years ago.
So I am developing a class for vectorial calculations, and I overwrote the __mul__(self, b) function to do a Scalarproduct. Now whenever I write A * B it calculates as I want it to. So I would like to do the same with an x for the Crossproduct. Sadly there is no default x operator in python, it would probably just annoy you. But is there a way to create your own operator which ONLY works for my own class, but can otherwise be used in a code aswell (as a variable definition I mean)? Or maybe define *** as an operator?
Instead of just define an operator, you can write your own interpreter for your own language inside python. Basically, you need to create 4 modules
parser
environment
eval
repl
Then you can program with your own language within python.
read Peter Novig's article for a detailed example of a python LISP interpreter
This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 8 years ago.
How could I integrate multiple values as parameters without using a tuple or a list? Does python have overloaded parameters?
I'm thinking something like this:
add(1,2) # 3
add(1,2,3,4) # 10
def add(numbers):
return sum(list(numbers))
Thanks in advance.
You are probably looking for Arbitrary Argument List.
However, you are probably doing more work than you need to and also I am not entirely sure what you are exactly trying to do (or what you mean by efficient algorithm), but the sum builtin function already does what you needed, you just need to read the documentation on what it actually expects in its arguments.
>>> sum([1,2,3])
6
>>> sum([1,2,3,4,5,6])
21
Or heck, if you want to go without a list or tuple (actually, arguments are a list already so you are just using unnecessary syntactic sugar) you can just do this then.
def add(*numbers):
return sum(numbers)
Just think a little and you can put together the above function.