Navigation

What are some hidden features of Python?

I always wanted to write something about this, but nearly all my knowledge about hidden things comes from this topic, sooo everything I knew probably isnt that much help
What are some hidden features of Python


I always wanted to write something about this, but nearly all my knowledge about hidden things comes from this topic, sooo everything I knew probably isnt that much help.
But now I know some things I can talk about (focussing on things not written here already!), mainly for all those guys and gals out there that want to optimize the hell out of their code and other unknown stuff

Disassemble Python
Ever thought about what python does under the hood? With the standard library module dis, you can do that easily!
  1. import dis
  2. def test(number):
  3. return (str(number)+str(number))
  4. dis.dis(test)
  5.  
  6. Result:
  7. 8 0 LOAD_GLOBAL 0 (str)
  8. 3 LOAD_FAST 0 (number)
  9. 6 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
  10. 9 LOAD_GLOBAL 0 (str)
  11. 12 LOAD_FAST 0 (number)
  12. 15 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
  13. 18 BINARY_ADD
  14. 19 RETURN_VALUE
  15. #can we speed it up?
Type hints
Everyone and their mum knows that Python is dynamically typed. But since a short while ago (some will probably know that) you can add type hints to your functions, and then use extern static type checking tools (like mypy) to check your code, without even running it.
And the best: You CAN use it, but it wont be enforced to you. Take that, enemies of dynamically typed languages.
Transposing a Matrix
Read that somewhere on Quora, dont know where sadly, but you can EASILY transpose an array made up of lists (no numpy) with the zip operation:
  1. matrix=[(1,2,3) , (4,5,6), (7,8,9)]
  2. for row in matrix:
  3. print(row)
  4. (1, 2, 3)
  5. (4, 5, 6)
  6. (7, 8, 9)
  7.  
  8. matrix2=zip(*matrix)
  9. print()
  10. for row in matrix2:
  11. print(row)
  12.  
  13. (1, 4, 7)
  14. (2, 5, 8)
  15. (3, 6, 9)
cProfile
Python has many scripts that are very useful. For example you can easily profile your code by starting your code like this:
python -m cProfile filename
With this, you then get an analysis of which function take how long, so you can always optimize the longest running function.
It will then look like this:



Found on google
Let me know if I could help you.


>> Also you can read: Disadvantages of the Python language over C++
مشاركة

أضف تعليق:

0 comments: