Python: "#" followed by a function -> What does it stand for? [duplicate] - python

This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
Closed 8 years ago.
I'm currently learning Python and I came across a notation I was wondering about:
import taskmanager as tm
#........
#tm.task(str)
def feat(folder):
BLA BLA BLA ...
the code is a small excerpt from https://github.com/kfrancoi/phd-retailreco/blob/master/libraries/plsa/example_plsa.py (the file contains several more notations using the # sign).
Is this a common notation in python and what does it mean? Or is this only a notation used in this special case with the taskmanager or what!?
I tried my best looking this up on google but it's though to find as the #-sign is stripped out in my search (too short, special character). Same happens here on Stackoverflow.
Thank you very much in advance

This a decorator, defined by the PEP 318. Extract of the glossary:
A function returning another function, usually applied as a function transformation using the #wrapper syntax. Common examples for decorators are classmethod() and staticmethod().
The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:
def f(...):
...
f = staticmethod(f)
#staticmethod
def f(...):
...
The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.
Related: What are some common uses for Python decorators?

Related

How can realize this code without concatenation? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 8 months ago.
How else can I implement a function without using ' '.join(str, name). I use this to convert tuple to str. And function def get_text should look:
def get_text(name):
return "Hello " + name
Is there another way to implement that?
def bold(get_text):
def wrapped(*name):
return "<b>{}</b>".format(get_text(" ".join(map(str, name))))
return wrapped
def italic(get_text):
def wrapped(name):
return "<i>{}</i>".format(get_text(name))
return wrapped
def underline(get_text):
def wrapped(name):
return "<u>{}</u>".format(get_text(name))
return wrapped
#bold
#italic
#underline
def get_text(*name):
return "hello " + " ".join(map(str, name))
print(get_text('Hi', 'world'))
Function returns:
<b><i><u>hello Hi world</u></i></b>
First of all, you try to re-invent wheel. If you want to make html/xml etc. page from python - there are already libraries/frameworks and tutorials for this, that will suit you much better.
However, if it's just he beginning of your programming journey, string manipulation is one of first steps.... however you also have tons of tutorials for this. Python has multiple methods to format strings (best depends on usage, really)... e.g.
fstrings (https://realpython.com/python-f-strings/)
string format (https://www.w3schools.com/python/ref_string_format.asp)
strings concatenation (but you want to avoid that one)
Basically, string documentation is where you want to look (also, tutorials above will do the trick as well)
What you are attempting to use here is using decorators - you've possibly looked to tutorial about decorators instead strings (this is quite nice and easy example to learn decorators, but decorators itself are quite complex for starters and can be confusing...)
For basic idea, decorators are methods, that wraps around another methods... let's say, you want to log time before method and after it. You could do that in that methods body, but your method should only be focused on doing one thing. E.g. method add should only add not, measure time, add, then measure time. Also, this binds measuring to your method - therefore you cannot use your method without measurement. Doesn't sound too flexible, and starts to be bit messy too...
So decorator is a nice way to have your 'inner' method body clean and focused on its role, but extending it with another functionality... Wrapping method and inner method are also independent (most of cases), and can be quickly separated... Also imagine, that you want to measure time of 'a lot of' your methods, but not every - so you put that decorator only with those methods, you want.

Use of # in Python [duplicate]

This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
Closed 2 years ago.
I was seeing the methods and docs of the built in super() method of python using the help() function in the IDLE .
I came across this piece of code
This works for class methods too: | class C(B): | #classmethod | def cmeth(cls, arg): | super().cmeth(arg)
In the second line , you can see the # sign before classmethod .
What does the # symbol does in python and what are its uses ?
The # character denotes a decorator. Decorators are functions that can modify or extend behavior of another function temporarily by wrapping around them.
Decorators wrap around a function by receiving them as a parameter. The # syntax (also known as "pie" syntax) applies the classmethod decorator to cmeth after it is defined in your snippet.
You can read more about the specific decorator from your example (classmethod) here.

Function parameter with colon [duplicate]

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 3 years ago.
I just came across this function:
def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[2])
I am aware that you can separate parameters by , or can set a value within a parameter like a=39 but I have not seen a colon like line:str. I have checked the function definition online but could not find anything like this. What does this colon mean?
It's a function annotation; function arguments and the return value can be tagged with arbitrary Python expressions. Python itself ignores the annotation (other than saving it), but third-party tools can make use of them.
In this case, it is intended as type hint: programs like mypy can analyze your code statically (that is, without running it, but only looking at the source code itself) to ensure that only str values are passed as arguments to splitComma.
A fuller annotation to also specify the return type of the function:
def splitComma(line: str) -> str:
...
(Note that originally, function annotations weren't assumed to have any specific semantics. This is still true, but the overwhelming assumption these days is that the annotations provide type hints.)
This is a type annotation used by static analysis tools to check, well, types. It helps ensure program correctness before you run the code.

Difference in using self and this in python [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 6 years ago.
Well, I am a newbie in Python and I am not able to understand the difference in using self and this keywords in Python.
This is the code that uses self as parameter :
class restaurant():
bankrupt = False
def open_branch(self):
if not self.bankrupt:
print("branch open")
x=restaurant()
print(x.bankrupt)
y=restaurant()
y.bankrupt=True
print(y.bankrupt)
And this is the code that uses this as parameter :
class restaurant():
bankrupt = False
def open_branch(this):
if not this.bankrupt:
print("branch open")
x=restaurant()
print(x.bankrupt)
y=restaurant()
y.bankrupt=True
print(y.bankrupt)
Both these approaches gave me the same output. So I m not able to understand why we use self when this solves our problem. Maybe my interpretation of self is wrong. I looked a lot of internet stuff but did not found anything relevant.
Can anyone please solve my issue.
It is mentioned in Python document:
Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.
Using the name self is just a (strong) convention.
You are free to use any name instead, as long as you are constant.
It is highly recommended to use self though.
In general, Python gives you a lot of freedom doing things the way you like.
On the other hand, there are many conventions like how to name you variables (compare PEP8). In 99% of the cases it is best to adhere to this conventions. But if you a 1% case, you can do it differently. I have never seen a case for not using the name self though.
PEP8 recommends the use of self:
Always use self for the first argument to instance methods.

How methods work in python? [duplicate]

This question already has an answer here:
python string module vs str methods
(1 answer)
Closed 6 years ago.
I am new to programming therefore may sound idiotic. I am learning python where I am not able to understand how few methods like upper(), split() etc work.
I mean you directly use like below:
"ABC".upper() or "abc,xyz".split(",")
Or, you can first import string and then call these methods like below:
import string
string.upper("abc")
string.split("abc,xyz", ",")
What is the difference, and how would we import string module when we can achieve the same output without importing it.
Are there similar cases exist apart from string module?
In fact, one of the paradigm you can use in Python is the Object Oriented Programming, where you modify object state through "methods" like this: myobject.mymethod().
Syntactically, it means that the first argument of the method mymethod() is in fact the object itself. But, as Python want also to deal with other paradigms (functional programming, imperative programming, and so on), there is two syntactical ways to address this method.
One is simply as I mentioned before: myobject.mymethod(), and the other one is simply to consider that the first argument is the object itself: mymethod(myobject).
More precisely, you can realize that when you define by yourself a method because you have to specify the first argument by self which is a reference to the object itself like this:
def mymethod(self):
pass

Categories

Resources