# operator at the beginning of the line in python [duplicate] - python

This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
Closed 4 years ago.
I'm trying to understand what does this operator #, uses in python.
I saw something about matrix multipication , but this is sure not the case,I'll give an example:
#property
def num_reserved_ids(self):
return 0
Or:
#registry.register_problem()
class LibrispeechNoisy(Librispeech):
Last one:
#registry.register_hparams
def transformer_librispeech_tpu_v1():
"""HParams for training ASR model on Librispeech on TPU v1."""
hparams = transformer_librispeech_v1()
update_hparams_for_tpu(hparams)
Registry is another file that is used in the program.register_hparams is a function inside.
Don't know what "property" is, but even registry that I know what it is, I can't understand the purpose of the operator :#, I'm a bit slow, sorry for that :/ ..
If anyone wants to look for some more code you can check tensor2tensor library:
https://github.com/tensorflow/tensor2tensor/tree/master/tensor2tensor

I think what you are looking for is called PythonDecorators
Here is the Wiki For Python Decorators
A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.
The best way to understand them is from Corey Schafer's Video on Python Decorators

Related

Python - forcing function inputs [duplicate]

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

How can I find the builtin function code? [duplicate]

This question already has answers here:
Finding the source code for built-in Python functions?
(8 answers)
Closed 2 years ago.
I just want to take a look builtin function code. Because I'm a beginner on Python and I think some source code can give me very useful instruction. I made some test code as follows and I did 'Ctrl+click' on 'join' with PyCharm IDE.
zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
And then cursor points builtin.py module's join function, but there is empty code. There is only an explanation. How does this operate? Where is the real code?
def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__
"""
Concatenate any number of strings.
The string whose method is called is inserted in between each given string.
The result is returned as a new string.
Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
"""
pass
'builtin.py' path is : C:\Users\admin.PyCharmCE2019.3\system\python_stubs\542861396\builtins.py
str.join() is implemented in C, specifically in unicodeobject.c at unicode_join.
"How can I find the source code for builtin functions and objects" doesn't have a great answer. See Finding the source code for built-in Python functions? for some overviews of how CPython is laid out. While some of Python's standard library is written in Python (this sits in lib/), you'll find that builtins and some performance-sensitive components of the standard library have a C implementation. The former resides in objects/, and the latter in modules/.

Create a calculations operator in python [duplicate]

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

Python Read-Only Properties are writable [duplicate]

This question already has answers here:
Private members in Python
(9 answers)
Closed 8 years ago.
I have the following Python-Code. I just can't get
the instance variable to be read only. Help appreciated.
class Parrot(object):
def __init__(self):
self._voltage = '100000'
#property
def voltage(self):
"""Get the current voltage."""
return self._voltage
a = Parrot()
print(a._voltage)
a._voltage = '500000'
print(a._voltage)
Edit:
The point of this question was to understand, how a property could replace the old
variable. Somehow everybody just points out that Python is about being mature, and
that it is our responsibility not to use "private" variables, since they are
visible in python. But nobody pointed out that you'd just turn the old variable in
this case
voltage
private
_voltage
and replace the old variable (voltage) with the property
#property
def voltage(self):
which would leave the way you access attributes in this class the same, so that nobody
who uses this class has to change their code.
-- like the way you access variables, since
you can still access the property like a variable -- e.g.:
a.voltage = 'over 9000'
But it gives more control to the developers of this class (turn voltage to read only). I just
felt that nobody did actually explain the mechanics of properties in an understandable way...
-> I was not able to understand properties although I googled first.
Anyways... kinda ridiculous, since it does not seem to pose any kind of difficulties now.
Cheers
Nimi
That's normal, since Python isn't a bondage & discipline language.
There's no real equivalent to 'private', but sometimes attributes with two leading underscores are used, though these are inteded to avoid problems when inherating.
The one leading underscore is just to avoid importing this when using a from xx import * import.

python 3.4.1 itertools documentation syntax lambda( x,_:r*x*(1-x) [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 years ago.
The python 3.4.1 Functional Programming documentation provides examples of itertools. It is section 10.1 under the Functional Programming section 10.0. There is a lambda function defined with the syntax: (The value of r is set elsewhere in the example.)
lambda(x,_:r*x*(1-x))
I have not seen the _ syntax as above. Can someone explain the _ please. In Erlang the _ would match a "don't care". I don't know what it does here.
Thank you.
_ is a variable like any other. The name _ is typically used for variables we don't care about, though this is just a convention; the value isn't automatically discarded or anything.

Categories