Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice for C# programmer writing Python [closed]

Tags:

python

c#

I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#.

Any advice on how I can fully take advantage of Python?

Or any tips\tricks, things to learn more about, things to watch out for?

like image 446
Gern Blanston Avatar asked Mar 25 '09 20:03

Gern Blanston


People also ask

What should I learn in C language?

By learning C, you will be able to understand and visualise the inner workings of computer systems (like allocation and memory management), their architecture and the overall concepts that drive programming. As a programming language, C also allows you to write more complex and comprehensive programs.

Is C easy for beginners?

Which programming language is easy to learn? C and C++ are both somewhat difficult to learn to program well. However, in many respects, they share many similarities with many other popular languages. In that sense they're just as easy (or as difficult) to learn, at first, as anything other programming language.


2 Answers

First, check tgray's and Lundström's advice.

Then, some things you may want to know:

  • Python is dynamically typed, so unlike C#, you will not check type, but behavior. You may want to google about duck typing. It implies you do not have to deal with boxing and unboxing.

  • Python is fully object oriented, but the syntax does not enforce this paradigm. You can write Python without using the word "class".

  • The GUI library featured with Python can't compare with C#'s. Check PyQt, GTK or wxPython libraries.

  • Python has a lot of concepts you may not be familiar with: list comprehensions, generators ("yield" does exist in C#, but it is not used much), decorators, metaclasses, etc. Don't be afraid; you can program in Python without them. They are just smart tools, not mandatory.

  • Like in C#, the Python standard library is huge. Always look at it when you encounter any problem. It is most likely that someone solved it already.

  • Python use LATE binding and variable labels. It's far too early for somebody starting with the language to worry about it, but remember that one day you will encounter a behavior with variables that SEEMS illogical, and you'll have to check that. For the moment:

Just remember to never do the following:

def myfunc(my_list=[]) :    # bla 

Instead:

def myfunc(my_list=()) :    my_list = list(my_list) 

And you'll be good. There is a good reason for that, but that's not the point :-)

  • Python is cross platform, enjoy writing on Mac, and run on Linux, if you wish.

  • Python is not provided with a complex IDE (you got IDLE :-)). If you are a Visual Studio addict, check Glade. This is not as advanced as Visual Studio, but it's still a good RAD.

  • If you want to develop some web application in Python, remember that Python is not .NET. You must add a web framework to it if you want to compare. I like Django.

  • Python does not need a huge IDE to work with. SciTE, Notepad++, IDLE, Kate, gedit... Lightweight editors are really sufficient.

  • Python enforces indentation using spaces and line break, you can't change that. You should avoid using tabs for indenting and choose spaces instead. The equivalent of empty bracelets {} is the keyword "pass".

  • Python does not enforce private variables. You can define a private var using "__" (two underscores) at the beginning of the variable name, but it's still bypassable in some tricky ways. Python usually assume programmers are grown adults that know what they do and communicate.

  • Python uses iteration. A lot. A lot of a lot. And so the itertools module is you best friend.

  • Python has no built in delegates. The delegate module is not what you think. For event-driven programming, use a GUI lib (or code the pattern yourself, it's not that difficult).

  • Python has an interpreter: you can test almost anything, live. It should always be running next to your text editor. Python basic interpreter is not much, try IPython for something tasty.

  • Python is autodocumented: use docstrings in your own code and consult other's using "help()" in the python interpreter

Module basics:

  • sys: manipulate system features
  • os: set credential, manipulate file paths, rename, recursive file walk, etc
  • shutil: batch file processing (such as recursive delete)
  • re: regexp
  • urllib and urllib2: HTTP¨scripting like downloading, post / get resquests, etc.
  • datetime: manipulate date, time AND DURATION
  • thread: you guess it
  • zlib: compression
  • pickle: serialization
  • xml: parsing / Writing XML with SAX or DOM

There are hundreds of modules. Enjoy.

Some typical ways to do things in Python:

Loops:

Python coders use massively the equivalent of the foreach C# loop, and prefer it to any others:

Basic iterations:

for item in collection:     print str(item) 

"collection" can be a string, a list, a tuple... Any iterable: any object defining the .next() method. There are a lot of iterables in Python. E.g: a typical Python idiom to read files:

for line in open("/path/to/file") :     print line 

A shortcut to the for loop is called "list comprehension". It's a way to create an new iterable in one line:

Creating a filtered list with list comprehension:

my_list = [item for item in collection if condition] 

Creating a new list with a list comprehension:

my_list = [int(item) * 3 for item in collection] 

Creating a new generator with a list comprehension:

my_list = (int(item) * 3 for item in collection) 

Same as above, but the values will be generated on the fly at the first iteration then lost. More information about it here.

Ordinary for loop

If you want to express a usual for loop, you can use the xrange() function. for (int i = 0; i < 5; i++) becomes:

for i in xrange(0,5) : 

do while equivalent

There is no "Do While" in Python. I never missed it, but if you have to use this logic, do the following:

while True : # Yes, this is an infinite loop. Crazy, hu?    # Do your stuff    if condition :       break 

Unpacking

Swapping variables:

a, b = b, a 

Multiple assignations:

The above is just a result of what we call "unpacking" (here applied to a tuple). A simple way to explain it is that you can assign each value of any sequence directly to an equal number a variables, in one row:

animal1, animal2, animal3, animal4 = ["cow", "dog", "bird", "fish"] 

This has a lot of implications. While iterating on a multidimensional array, you normally get each sub sequence one by one then use it, for example:

agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")] for person in agenda:     print person[0], person[1] 

But with unpacking, you can assign the values directly to variables as well:

agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")] for name, lastname in agenda:     print name, lastname 

And that's why if you want to get an index while iterating, Python coders use the following idioms (enumerate() is a standard function):

for index, value in enumerate(sequence) :     print index, value 

Unpacking in functions calls

This is advanced use, and you can skip it if it bothers you.

You can unpack values using the sign "*" to use a sequence directly in a function call. E.g:

>>> foo(var1, var1, var3) :     print var1, var2     print var3 >>> seq = (3.14, 42, "yeah") >>> foo(*seq) 3.14 42 yeah 

There is even more than that. You can unpack a dictionary as named variables, and write function prototypes with *, ** to accept an arbitrary number of arguments. But it not used enough to deserve to make this post even longer :-).

String formatting:

print "This is a %s on %s about %s" % ("post", "stackoverflow", "python") print "This is a %(subject)s on %(place)s about %(about)s" % {"subject" : "post", "place" : "stackoverflow", "about" : "python"} 

Slicing an iterable:

You can get any part of an iterable using a very concise syntax:

print "blebla"[2:4] # Print "eb" last = string[:-1] # Getting last element even = (0,1,2,3,4,5,6,7,8,9)[::2] # Getting evens only (third argument is a step) reversed = string[::-1] # Reversing a string 

Logical checks:

You can check the way you do in C#, but there are "Pythonic" ways (shorter, clearer :-)):

if 1 in (1, 2, 3, 4) : # Check en element is in a sequence  if var : # check is var is true. Var == false if it's False, 0, (), [], {} or None  if not var : # Contrary of above  if thing is var: # Check if "thing" and "var" label the same content.  if thing is None : # We use that one because None means nothing in Python (almost null) 

Combo (print on one line all the words containing an "o" in uppercase ):

sentence = "It's a good day to write some code" print " ".join([word.upper() for word in sentence.split() if "o" in word]) 

Output: "GOOD TO SOME CODE"

Easier to ask for forgiveness than permission

Python coders usually don't check if something is possible. They are a bit like Chuck Norris. They do it. Then catch the exception. Typically, you don't check if a file exists, you try to open it, and roll back if it fails:

try :     f = open(file) except IOerror :     print "no file here !" 

Of course Chuck Norris never uses excepts since he never fails.

The else clause

"Else" is a world of many uses in Python. You will find "else" after "if", but after "except" and "for" as well.

for stuff in bunch :     # Do things else :     # This always happens unless you hit "break" in the loop 

This works for "while" loop too, even if we do not use this loop as much.

   try :       # A crazy stuff    except ToCrazyError :       # This happens if the crazy stuff raises a ToCrazyError Exception    else :       # This will happen if there is no error so you can put only one line after the "try" clause    finally :       # The same as in C# 

If you are curious, here is a bunch of advanced quick and dirty (but nice) Python snippets.

like image 138
15 revs, 5 users 63% Avatar answered Oct 07 '22 07:10

15 revs, 5 users 63%


  • Refrain from using classes. Use dictionaries, sets, list and tuples.
  • Setters and getters are forbidden.
  • Don't have exception handlers unless you really need to - let it crash in style.
  • Pylint can be your friend for more pythonish coding style.
  • When you're ready - check out list comprehensions, generators and lambda functions.
like image 36
Stefan Lundström Avatar answered Oct 07 '22 08:10

Stefan Lundström