What would you like to know about when you started learning Python?

I decided to learn Python 3. For those who used to be, what did you find most useful along the way and want you to know about it before?

+45
python
Nov 10 '09 at 19:01
source share
29 answers

I learned Python before the release of 1.5.2, so the things that were key to me then for me may not be important today.

This, as they say, is an important thing that understood me a little, but now I consider it decisive: many of the functionality that other languages ​​do internally, in fact, become available as a standard library and built-in modules.

The language itself is small and simple, but until you are familiar with the built-in modules and the "main parts" of the standard library (for example, currently sys , itertools , collections , copy , ...), you will reinvent the wheel again and again. Thus, the more time you invest in familiarizing yourself with these parts, the more smooth your progress will be. Every time you have a task that you want to do, it does not seem to be supported directly by the language, first ask yourself: which built-in modules or modules in the standard library will make the task much easier or even do it all for me? Sometimes they will not be, but most often you will find excellent solutions based on this thinking.

+56
Nov 10 '09 at 19:07
source share
  • I'm sorry that I do not know Java.
  • More functional programming. (see itertools module, list comprehension, map (), reduce () or filter ())
+31
Nov 10 '09 at 19:03
source share

List comprehension (makes the list clean):

 [x for x in y if x > z] 

Generator extension (same as list comprehension, but not evaluated before use):

 (x for x in y if x > z) 
+27
Nov 10 '09 at 19:03
source share

Two convulsive cramps. One of them does not apply to Python 3.

 a = 095 

Does not work. What for? The leading zero is an octal literal. 9 is not valid in octal literal.

 def foo( bar=[] ): bar.append( 1 ) return bar 

Does not work. What for? The changed default object is used again.

+25
Nov 10 '09 at 19:20
source share
  • For enumerate .
  • For seq = seq.append(item) and seq = seq.sort() set seq to None .
  • Using set to remove duplicates.
  • Quite a lot of things in itertools and collections modules.
  • How the prefixes * and ** for function arguments work.
  • How default argument parameters work internally (i.e. that f.func_defaults ).
  • How (why, really) to create functions so that they are useful in combination with map and zip .
  • The role of __dict__ in classes.
  • Actually import .
+19
Nov 10 '09 at 22:53
source share

Learn how to use iPython. He got a tab. Browse through all the elements in your whos namespace.

After importing the module, you can easily view the code:

 >>> import os >>> os?? # this display the actual source of the method >>> help() # Python interactive help. Fantastic! 

Most Python modules are well documented; in theory, you could learn iPython, and the rest of what you need to know could be learned using the same tool.

iPython also has debug mode, pdb (). Finally, you can even use iPython as a command line with python support. Basic UNIX commands work like% magic methods. Any commands that are not magic commands can be executed:

 >>> os.system('cp file1 file2') 
+17
Nov 10 '09 at 19:07
source share

They do not have variable names that are types. For example, do not name the variable "file" or "dict"

+16
Nov 10 '09 at 19:06
source share

Decorators. Writing your own is not something you might want to do right away, but knowing that @staticmethod and @classmethod are available @classmethod from the start (and the difference between what they do) is a real plus.

+13
Nov 10 '09 at 19:21
source share
  • using help() in a shell on any object, class or path
  • you can run import code; code.interact(local=locals()) import code; code.interact(local=locals()) anywhere in your code and it will launch the python shell at that exact point
  • you can run python -i yourscript.py to start the shell at the end of yourscript.py
+7
Nov 10 '09 at 22:56
source share

Most useful: Immersion in Python . As the commentator notes, if you are learning Python 3, Dive Into Python 3 is more applicable.

Known Before: virtualenv .

+5
Nov 10 '09 at 19:03
source share

That a tuple of one element must end with a comma or it will not be interpreted as a tuple.

pprint() very convenient (yes, 2 p)

reload() is useful when you re-test a module, making many quick changes to the dependent module.

And learn as many ordinary “idioms” as possible, otherwise you will be banging your head trying to find the best way to do something when the idiom is really considered the best way (for example, ugly expressions like ' '.join() , or the answer to the question why there is no function isInt(string) .... Answer: you can simply wrap the use of a "possible" integer with try: and then catch the exception if it is not a valid int. well, but that sounds like a terrible answer when you first encounter with him, so you can spend a lot of time convincing yourself That is a really good approach.

Here are some things that took several hours of my time to determine that my first draft of some code that was considered incorrect was indeed acceptable.

Readings from python.org:

http://wiki.python.org/moin/BeginnerErrorsWithPythonProgramming http://wiki.python.org/moin/PythonWarts

+5
Nov 12 '09 at 2:55
source share

List of concepts if you are coming to a new Python (not from an earlier version).

+4
Nov 10 '09 at 19:05
source share

Closures. Clean and concise, without resorting to using a strategy template, unlike languages ​​such as Java

+4
Nov 10 '09 at 19:09
source share

If you learn from a good book, it will not only teach you the language, but also teach you common idioms. Idioms are valuable.

For example, here is a standard idiom for initializing an instance of a class with a list:

 class Foo(object): def __init__(self, lst=None): if lst is None: self.lst = [] else: self.lst = lst 

If you learn this as an idiom from a book, you don't need to study hard why this is a standard idiom. @ S.Lott already explained this: if you try to make the default initializer empty, the empty list will be evaluated only once (at compile time), and each default initialized instance of your class gets the same list instance that was not what intended here.

Some idioms protect you from unwanted effects; some of them will help you get better language performance; and some of them are just small style points that help other Python fans to better understand your code.

I learned from the Learning Python book and introduced me to some idioms.

Here is the idiom webpage: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

PS The Python code that follows the most practical Python idioms is often called the "Pythonic" code.

+4
Nov 10 '09 at 21:00
source share

I implemented many recursive directory walks manually before I found out about os.walk ()

+4
Nov 10 '09 at 21:47
source share
+3
Nov 10 '09 at 19:17
source share

One of the coolest things I recently learned about was the command module:

 >>> import commands >>> commands.getoutput('uptime') '18:24 up 10:22, 7 users, load averages: 0.37 0.45 0.41' 

This is similar to os.popen or os.system, but without all the DeprecationWarnings exceptions.

And don't forget the PDB (Python debugger):

 % python -m pdb poop.py 
+3
Nov 11 '09 at 2:26
source share

Going Interactive in IPython

 from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell() 
+3
Nov 11 '09 at 11:51
source share

When I started with python, I started with the basic methods from the examples. This happened because I did not know which was better, after which I found this on how to create a better main method.

+3
Nov 11 '09 at 13:30
source share

I'm sorry that I did not know how to write code in Python correctly. You can choose any language that you like and start coding in it, like in C, Java, etc., But ideally you will learn how to code the "spirit" of the language. Python is especially relevant as I think it has a specific style of its own.

While I found this a little later in my Python career than I would have liked, this great article covers many of the Python idioms and small tricks that make it special. Some of the things that people mentioned so far in their answers are contained in: Code Like Pythonista: Idiomatic Python .

Enjoy it!

+2
Nov 10 '09 at 22:17
source share

Serial import is overwritten:

If you import two files, for example:

 from foo import * from bar import * 

If both foo.py and bar.py have a function called fubar (), then when you import files this way, when you call fubar, fubar will be executed, as defined in bar.py. The best way to avoid this is to do this:

 import foo import bar 

and then call foo.fubar or bar.fubar. This way, you ALWAYS know which fubar file definition will be executed.

+2
Nov 12 '09 at 16:23
source share

Perhaps more advanced, but I wish I knew you were using threads to use multiple cores in (C) python. You are using the multiprocessing library.

+2
Nov 16 '09 at 14:50
source share

Tab completion and general readline support, including stories, even in a regular python shell.

 $ cat ~/.pythonrc.py #!/usr/bin/env python try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") import os histfile = os.path.join(os.environ["HOME"], ".pyhist") try: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile 

and then add the line to your .bashrc

 export PYTHONSTARTUP=~/.pythonrc.py 

These two things lead to a searchable style of programming "it looks like this library can do what I want," so I run the python shell and then pass around with the tab-completion and help () command until I find that's what I need.

Generators and a list of concepts are more useful than you think. Don't just ignore them.

+2
Nov 17 '09 at 0:48
source share

I wish I knew a functional language well. Having lost a bit with Clojure, I realized that many Python functional ideas are borrowed from Lisp or other functional languages

+1
Nov 10 '09 at 21:43
source share

Pretty print:

 >>> print "%s world" %('hello') hello world 

% s for row

% d for integer

% f for float

% xf for exactly x many decimal places of the float. If the float has smaller decimal numbers that are specified, then 0s is added

+1
Nov 12 '09 at 16:27
source share

I really like the understanding of lists and all the other semi-rigid constructs. I wish I knew this when I was in my first Python project.

0
Nov 10 '09 at 19:04
source share

What I really liked: a list of concepts, closures (and high-order functions), tuples, lambda functions, painless binoculars.

What I would like to know before: the fact that using Python idioms in code (for example, for lists, and not for loops over lists) was faster.

0
Nov 10 '09 at 20:37
source share

This is a multi-core future. Still love Python. He writes my code for me.

0
Nov 10 '09 at 21:49
source share

Functional programming tools like all and any

0
Jun 17 2018-11-17T00:
source share



All Articles