This question already has answers here:
Python 3.5 type hinting does not result in an error
(2 answers)
Closed 2 years ago.
I want to force that arg to function will be str , so I used :str into function args
def func (a:str):
print(a)
func(int(2))
This code is work and didn't fail , why?
def func (a:str):
print(a)
func(int(2))
What you have used is Type Hint as described PEP 484. Shortly speaking it is only guideline and do not have any enforcing effect. You might use isinstance function for checking if argument conforms to your requirement and raise TypeError otherwise following way:
def func(a):
if not isinstance(a, str):
raise TypeError
print(a)
You can also (alongside the runtime check or instead of it) use a static type checker which will attempt to leverage those annotations (and possibly what it can infer from the un-annotated code) and check that they all match. By default Python (wilfully and knowingly) includes syntax to add type hints, but will not perform any type checking: that's not considered part of the python language itself (although there are parts of python which use the type annotations, like dataclasses).
The premier type-checker is mypy and developed under the umbrella of the Python project, but there are various alternatives (I've not necessarily tested so YMMV) e.g. Facebook's pyre, google's pytype or microsoft's pyright, as well as integrated tools such as the built-in type-checking of IDEs like jetbrains'.
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.
This question already has answers here:
What do square brackets, "[]", mean in function/class documentation?
(4 answers)
Closed 6 years ago.
I have a problem understanding some description of functions in Python.
I understand simply functions like os.putenv(varname, value) but I have no idea how to use this: os.getenv(varname[, value]). How to pass arguments to that function, what does those square brackets mean?
Square brackets typically mean that the value is optional. Here, varname refers to the environment variable you want to get and value is an optional value that is return if the environment variable doesn't exist.
The square brackets indicate the argument is optional. Read the description:
Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.
So you can call it like this:
os.getenv('NONEXISTANTVAR')
or like this:
os.getenv('NONEXISTANTVAR', u'my default')
This first is equivalent to os.getenv('NONEXISTANTVAR', None). In the specific case of getenv, the second argument is returned if the environment variable doesn't exist.
Typically, the documentation will tell you the default value if you don't provide one, either explicitly in the description or by placing an =somevalue directly in the signature. If it doesn't indicate a specific value, then it will at least describe the difference in behavior.
unicode gives us an example of the = in the signature:
unicode(object='')
Note that in Python, the only way for an argument to be optional is for it to have a default value.
While I am aware of the duck-typing concept of Python, I sometimes struggle with the type of arguments of functions, or the type of the return value of the function.
Now, if I wrote the function myself, I DO know the types. But what if somebody wants to use and call my functions, how is he/she expected to know the types?
I usually put type information in the function's docstring (like: "...the id argument should be an integer..." and "... the function will return a (string, [integer]) tuple.")
But is looking up the information in the docstring (and putting it there, as a coder) really the way it is supposed to be done?
Edit: While the majority of answers seem to direct towards "yes, document!" I feel this is not always very easy for 'complex' types. For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?
The docstring PEP documentation doesn't give any guidelines on that.
I guess the counterargument will be that in that case classes should be used, but I find python very flexible because it allows passing around these things using lists and tuples, i.e. without classes.
Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:
def greeting(name):
return 'Hello, {}'.format(name)
can now be written as this:
def greeting(name: str) -> str:
return 'Hello, {}'.format(name)
As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.
for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.
This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.
Here are some strategies to avoid problems with duck typing:
create a language for your problem domain
this will help you to name stuff properly
use types to represent concepts in your domain language
name function parameters using the domain language vocabulary
Also, one of the most important points:
keep data as local as possible!
There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code...
Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!
Actually there is no need as python is a dynamic language, BUT if you want to specify a return value then do this
def foo(a) -> int: #after arrow type the return type
return 1 + a
But it won't really help you much. It doesn't raise exceptions in the same way like in staticly-typed language like java, c, c++. Even if you returned a string, it won't raise any exceptions.
and then for argument type do this
def foo(a: int) -> int:
return a+ 1
after the colon (:)you can specify the argument type.
This won't help either, to prove this here is an example:
def printer(a: int) -> int: print(a)
printer("hello")
The function above actually just returns None, because we didn't return anything, but we did tell it we would return int, but as I said it doesn't help. Maybe it could help in IDEs (Not all but few like pycharm or something, but not on vscode)
I attended a coursera course, there was lesson in which, we were taught about design recipe.
Below docstring format I found preety useful.
def area(base, height):
'''(number, number ) -> number #**TypeContract**
Return the area of a tring with dimensions base #**Description**
and height
>>>area(10,5) #**Example **
25.0
>>area(2.5,3)
3.75
'''
return (base * height) /2
I think if docstrings are written in this way, it might help a lot to developers.
Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI
Yes, you should use docstrings to make your classes and functions more friendly to other programmers:
More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
Some editors allow you to see docstrings while typing, so it really makes work easier.
Yes it is.
In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.
In the same way, the parameters don't always have to be the same type too.
For example: how to describe concisely in a docstring that a function returns a list of tuples, with each tuple of the form (node_id, node_name, uptime_minutes) and that the elements are respectively a string, string and integer?
Um... There is no "concise" description of this. It's complex. You've designed it to be complex. And it requires complex documentation in the docstring.
Sorry, but complexity is -- well -- complex.
Answering my own question >10 years later, there are now 2 things I use to manage this:
type hints (as already mentioned in other answers)
dataclasses, when parameter or return type hints become unwieldy/hard to read
As an example of the latter, say I have a function
def do_something(param:int) -> list[tuple[list, int|None]]:
...
return result
I would now rewrite using a dataclass, e.g. along the lines of:
from dataclasses import dataclass
#dataclass
class Stat:
entries: list
value: int | None = None
def do_something(param:int) -> list[Stat]:
...
return result
Yes, since it's a dynamically type language ;)
Read this for reference: PEP 257
Docstrings (and documentation in general). Python 3 introduces (optional) function annotations, as described in PEP 3107 (but don't leave out docstrings)
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).