Trace: » python02.html

[hemmerling] Python 2/10

Python - The Programming Language

Abstract methods, @classmethod, @staticmethod

Anonymous functions

Decorators - @ -

Duck Typing

if not

Metaclass

Regular Expressions

Example 1 - Extract

import re
filename = "file2016.txt"
match = re.search(r"[0-9{4}",filename)
match.group(0)

Example 2 - Replace

re.sub(r"[0-9{4}","2011",filename)

Resources

*vargs & **kwargs

Tips & Tricks

General

x = [1,2]
y = x
z = [x[0],x[1]]
print x, y, z
y[0] = 3
print x, y, z
  • Result of value copy and pointer copy
[1, 2] [1, 2] [1, 2]
[3, 2] [3, 2] [1, 2]

CodeSculptor

    • “The statement print 'Hello' works... However, print 7 / 3 gives 2.33333333 in CodeSkulptor, not 2 as in python2”.
    • “This is Python 2. However, it's implemented on top of JavaScript, so there's no integer/float distinction. To get integer division, use
      7 \\ 3

      , which would give 2”.

  • math.ceil():
    • Python 2.7.3: math.ceil() is a float.
    • CodeSculptor: math.ceil() is an integer.
      import math
      print math.ceil(7.5)
      print int(math.ceil(7.5))
      
  • type()
    • Python 2.7.3: type(2) is ”<type 'int'>”.
    • CodeSculptor: type(2) is ”<class 'int'>”.
      print type(2)
      
  • Improved input interactivity - How to set the focus on the input.
  • CodeSkulptor does not support try and with statements, offically :-(.
    • Error message “ReferenceError: goog is not defined”
    • Workaround for try.. except: Avoid references ( e.g. writing class variables or global variables ), but save data in local variables or do a return to next function level:-):
  • How to run CodeSculptor offline:
    • You can also save the page so that it gets everything ( called “Webpage, complete” ). It will save an HTML file and a folder with all the JS files.
    • The buttons will work but won't have their icons default; if you really want them, you can make a folder called “images” in the saved folder and drag the “ui-icons_00246a_256x240.png” into it.
    • This will let CS run completely offline, with images. Just remember to save locally since you are not connected to the cloud.
  • The random number sequence is different, with
    personal_random_seed = 1
    start = 1
    stop = 100
    step = 1
    random.seed(personal_random_seed) 
    random.randrange(start,end,step)
    
  • A CodeSculptor program can just run up to 5 seconds “in one block of Code”, else the Codesculptor runtime assumes a timeout and aborts operation, by the error message “Line 8: Error: Program exceeded run time limit”. See videos “Programming tips -6” and “Blackjack”.

Reflection

Reflection with Python 2.7.3 - Code Example

class Foo:
    def hello(self):
        print "Hello World"

# without reflection
obj = Foo()
obj.hello()

# with reflection
class_name = "Foo"
method = "hello"
obj = globals()[class_name]()
getattr(obj, method)()

Simulation of a Reflection with CodeSculptor - Code Example

global_dict = {}
def globals():
    return global_dict

class Foo:
    def hello(self):
        print "Hello World"

global_dict['Foo'] = Foo

# without reflection
obj = Foo()
obj.hello()

# with reflection
class_name = "Foo"
method = "hello"
obj = globals()[class_name]()
getattr(obj, method)()

Resources

Testing

Text Formatting

Indentation Problem

Error: Inconsistent indentation detected!
1) Your indentation is outright incorrect (easy to fix), OR
2) Your indentation mixes tabs and spaces.
To fix case 2, change all tabs to spaces by using 
Edit->Select All followed by Format->Untabify Region 
and speicfiy the number of columns used by each tab

Indentation Problem

Syntax error
There's an error in your program:
unindent does not match any outer indentation level

Windows Platform

Python File Extensions with Windows

  • pythonfile.py → DOS windows, i.e. error messages are printed on the “DOS Console”.
  • pythonfile.pyw → no DOS window, i.e. error messages are not printed on a “Console”.

Modules you should not try to install with "easy_install" on Windows, as Rookie :-(

  • You should not try to install “turtle”:
    • Any installation attempt is obselete, as it is already included in the distributions “Python(x,y)” and “Anaconda”.
    • Installation with “easy_install turtle” aborts with an error message “error: Unable to find vcvarsall.bat” which indicates that there is no proper “C” compiler chain implemented on the Windows computer. Afterwards the module “turtle” can still be imported in Python programs, but any access is denied by the error messages like “AttributeError: 'module' object has no attribute 'Screen'”. As rookie, you ruined your Python installation :-(, the only advice I can give you to deinstall and reinstall your Python completely.

Setting up a Compiler Chain to install Modules which need a working "C" Compiler Chain installed

Calling Pylint from PyScripter on Windows Platform

  • On Win8, 32bit, with Python 2.7.x, loading a file in MSDOS 8+3 style into PyScripter ( e.g.”reverseb.py” ), executing Pylint works fine.
  • But on Win8, 32bit, with Python 2.7.x, loading a file in Windows long filename style into PyScripter ( e.g.”reversebinary.py” ), executing Pylint causes an error message. You see that the call of Pylint is executed in MSDOS 8+3 mode, i.e. “REVERS~1.PY” is called:
Command line: C:\Python27\python.exe C:\Python27\Lib\site-packages\pylint\lint.py 
C:\Users\Public\projects\SPOTIF~1\REVERS~1.PY -f parseable

C:\Users\Public\projects\SPOTIF~1\REVERS~1.py:1: 
[C] Invalid name "REVERS~1" for type module
(should match (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$)

Process "Pylint" terminated, ExitCode: 00000010

List of all installed Python Modules

AttributeError: 'module' object has no attribute '__version__'

  • My case:
    • My problem: My application uses the Tkinter GUI framework GitHub "alejandroautalan/pygubu" and installs the application by distutils. If I call the application by commandline, there is the error message as “pygubu.py” is both the name of script in the folder “Scripts” ( which I don´t want to import, but which Python tries to import here ) and a name of a module of the application ( which I want to import here ).
    • My solution: Rename “Scripts/pygubu.py” to “Scripts/pygubu-script.py” and add a batch file “pygubut.bat” and “pygubu.sh” respectively, which just call “python pygubu-script.py”.
    • The error message:
      File "C:\Python27\lib\site-packages\codebreaker_package\pygubu_codebreaker.py", line 33, in <module>
          import pygubu
        File "C:\Python27\Scripts\pygubu.py", line 43, in <module>
          print("Pygubu: v. %s" % (pygubu.__version__,))
      AttributeError: 'module' object has no attribute '__version__'
      
  • Other cases:

Appropriate OpenDirectory Directory Pages

 
en/python02.html.txt · Last modified: 2024/04/18 20:51 (external edit) · []
Recent changes RSS feed Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki