Using Type Hints with Brackets [duplicate] - python

This question already has answers here:
Declaration of list of type python
(1 answer)
Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc
(2 answers)
Closed 10 months ago.
After several hours of chasing this error with an AWS Elastic Beanstalk app (Python 3.8), I learned that I can't use type hints with brackets, as seen below. But I don't understand why.
Per the docs, I see type hints as far back as at least 3.5 (I didn't look back further than this).
Does this have to do with the Python version, or something else?
doesn't work:
def func(x, y:list[str]):
pass
works:
def func(x, y:list):
pass

Related

Use of None and self keywords in method construction [duplicate]

This question already has answers here:
What does -> mean in Python function definitions?
(11 answers)
Python3 function definition, arrow and colon [duplicate]
(3 answers)
What does the -> (dash-greater-than arrow symbol) mean in a Python method signature? [duplicate]
(1 answer)
Closed 9 months ago.
I'm analyzing some old code that I've inherited, and I have a question about the use of "self" and "None" keywords, specifically in the following example:
def run(self) -> None:
I understand that the self keyword is similar to the "this" keyword in C++ in that, in conjunction with the dot operator, it allows us to access the attributes and methods of the class in question. What I'm really interested in is the use of "-> None" in the declaration of the method named "run." Is this in PEP 8 because I can't find an example. I'm using Python 3.7, in case that matters.
What is the purpose of writing a method in this manner? What does "-> None" do?
They're called type hints, and they enable annotating the types of the parameters and return types of functions.
https://peps.python.org/pep-0484/

Shouldn't "a:1" be a syntax error in python? [duplicate]

This question already has answers here:
What is this odd colon behavior doing?
(2 answers)
Closed 3 years ago.
I made a typo in my code that went completely silent syntactically.
dict_args : {"arg1":1,"arg2":2,"arg3":3}
# .... Some more code
some_function(**dict_args)
# .... Some more code
If you haven't noticed it, it's the use of : instead of = when declaring the variable dict_args.
So my question is, does the python syntax : a:1, by itself, hold any meaning ? Or should it hypothetically be considered a syntax error?
PEP-526 introduced variable annotations, which provide programmers a way to add type information to variables. This allows, among other things, statements like
x: int
to indicate that there is a local variable of type int, without initializing it. In PEP-484 - Acceptable Type Hints, we can see that annotations "must be valid expressions that evaluate without raising exceptions", which your dictionary literal is.
If you look at the Python grammar itself you can see that the expr_stmt and annassign rules make the example you show legal.
If you're using an IDE/other type hinting tools, they should definitely complain about this, but it doesn't break the rules that Python has set up.

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.

Accessing data in variables in class Python 3 [duplicate]

This question already has answers here:
Python: access class property from string [duplicate]
(4 answers)
Closed 4 years ago.
I am using Python 3.5 and wish to do something like this
I have created a class which has variables Bitcoin, Monero , 'Etherum' ,etc with various integer values ,I wish to extract them
var1="Bitcoin"
value=classobj.var1 // there is a class which has a variable called Bitcoin and its value is 10 I wish to get its value using classobject.Bitcoin but the variable called var is Dynamic
print (value)
How do I achieve the same ?
EDIT
I know it is possible using switch statement but I am looking for other ways
This is almost always a bad idea—and you really should explain why your design looks like this, because it's probably a bad design.
But "almost always" isn't "always", so Python has a way to do this:
getattr(classobj, var)

How to retrieve/know function's default values [duplicate]

This question already has answers here:
Get a function argument's default value?
(7 answers)
How to find out the default values of a particular function's argument in another function in Python?
(4 answers)
How can I read a function's signature including default argument values?
(9 answers)
Closed 5 years ago.
I am a python beginner and I currently struggle with some (probably quite simple) stuff. I would like to know the default parameters of a python function, more specifically of cv2.ORB_create().
With the following code I managed to see the 'documentation string':
import cv2
orb = cv2.ORB_create()
print(cv2.ORB_create.__doc__)
However, print(cv2.ORB_create.__defaults__) just gives me an error;
AttributeError: 'builtin_function_or_method' object has no attribute '__defaults__'
Maybe I am missing a link between functions, modules, etc. but I am really stuck...
Since the concern was brought up that this is a duplicate. I also tried inspect.signature and by extension inspect.getargspec, but this give me another error ValueError: no signature found for builtin <built-in function ORB_create>.
cv2.ORB_create() seems to be a function written with the Python extensions (In C instead of Python). As such, it isn't a "normal" function object, and there is no way to see the default values reliably (As it is handled manually in C).
One possible solution would be to look at the __text_signature__ attribute, but this may not be reliable. See What are __signature__ and __text_signature__ used for in Python 3.4.

Categories

Resources