Python Interview Questions

Python Interview Questions


1. What Is Python?

Python is an interpreter, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

2. Is There A Tool To Help Find Bugs Or Perform Static Analysis?

Yes.

PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style.

Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.

3. What Are The Rules For Local And Global Variables In Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.

Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

4. How Do I Share Global Variables Across Modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:

x = 0 # Default value of the 'x' configuration setting

mod.py:

Import config

config.x = 1

main.py:

Import config

Import mod

Print config.x

5. How Do I Copy An Object In Python?

In general, try copy.copy () or copy.deepcopy () for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

Newdict = olddict.copy ()

Sequences can be copied by slicing:

new_l = l [:]

6. How Can I Find The Methods Or Attributes Of An Object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

7. Is There An Equivalent Of C's "?:" Ternary Operator?

No

8. How Do I Convert A Number To A String?

To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'.

9. What's A Negative Index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of sew [-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

10. How Do I Apply A Method To A Sequence Of Objects?

Use a list comprehension:

Result = [obj.method () for obj in Li

11. What Is A Class?

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a data type.

A class can be based on one or more other classes, called its base class (es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessory methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, Outlook Mailbox that handle various specific mailbox formats.

12. What Is A Method?

A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition:

Class C:

Def meth (self, arg):

Return arg*2 + self. Attribute

13. What Is Self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

14. How Do I Call A Method Defined In A Base Class From A Derived Class That Overrides It?

If you're using new-style classes, use the built-in super() function:

Class Derived (Base):

Def meth (self):

Super (Derived, self).meth ()

If you're using classic classes: For a class definition such as class Derived (Base): ... you can call method meth () defined in Base (or one of Base's base classes) as Base. Meth (self, arguments...). Here, Base. Meth is an unbound method, so you need to provide the self argument.

15. How Do I Find The Current Module Name?

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:

Def main():

Print 'Running test...'

...

If __name__ == '__main__':

Main ()

__import__ ('x.y.z') returns

Try:

__import__('x.y.z').y.z

For more realistic situations, you may have to do something like

m = __import__(s)

For i in s.split (".")[1:]:

m = getattr (m, i)

16. Where Is the Math.py (socket.py, Regex.py, Etc.?) Source File?

There are (at least) three kinds of modules in Python:

1. Modules written in Python (.py);

2. Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);

3. Modules written in C and linked with the interpreter; to get a list of these, type:

Import sys

Print sys.builtin_module_names

17. How Do I Delete A File?

Use os.remove (filename) or os.unlink (filename);

18. How Do I Copy A File?

The shutil module contains a copy file () function.

19. How Do I Run A Sub process With Pipes Connected To Both Input And Output?

Use the popen2 module. For example:

Import popen2

From child, to child = popen2.popen2("command")

tochild.write ("inputn")

tochild.flush ()

Output = fromchild.readline ()

20. How Do I Avoid Blocking In The Connect () Method Of A Socket?

The select module is commonly used to help with asynchronous I/O on sockets.

21. Are There Any Interfaces To Database Packages In Python?

Yes.

Python 2.3 includes the buddy package which provides an interface to the Berkeley library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python.

22. How Do I Generate Random Numbers In Python?

The standard module random implements a random number generator. Usage is simple:

Import random

Random. Random ()

This returns a random floating point number in the range [0, 1).

23. Can I Create My Own Functions In C?

Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.

24. Can I Create My Own Functions In C++?

Yes, using the C compatibility features found in C++. Place extern "C" { ... } around the Python include files and put extern "C" before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.

25. How Can I Execute Arbitrary Python Statements From C?

The highest-level function to do this is PyRun_SimpleString () which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including Syntax Error).

26. How Can I Evaluate An Arbitrary Python Expression From C?

Call the function PyRun_String () from the previous with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value.

27. How Do I Interface To C++ Objects From Python?

Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.

28. How Do I Make Python Scripts Executable?

On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python. File) and gives that file type an open command that runs the interpreter (D: Program FilesPythonpython.exe "%1" %*). This is enough to make scripts executable from the command prompt as 'foo.py'. If you'd rather be able to execute the script by simple typing 'food' with no extension you need to add .py to the PATHEXT environment variable.

On Windows NT, the steps taken by the installer as described above allow you to run a script with 'foo.py', but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important.

The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line:

@setlocal enable extensions & python -x %~f0 %* & go to :EOF

29. How Do I Debug An Extension?

When using GDB with dynamically loaded extensions, you can't set a breakpoint in your extension until your extension is loaded.

In your .gdbinit file (or interactively), add the command:

Br _PyImport_LoadDynamicModule

Then, when you run GDB:

$ Gdb /local/bin/python

Gdb) run myscript.py

Gdb) continue # repeat until your extension is loaded

Gdb) finish # so that your extension is loaded

Gdb) br myfunction.c:50

Gdb) continue

30. Where Is Freeze For Windows?

"Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.

31. Is A *.pyd File the same as a Dll?

Yes.

32. How Do I Emulate Os.kill () In Windows?

Use win32api:

Def kill (PID):

""Kill function for Win32"""

Import win32api

Handle = win32api.OpenProcess (1, 0, pid)

Return (0! = win32api.TerminateProcess (handle, 0))

33. Explain About The Programming Language Python?

Python is a very easy language and can be learnt very easily than other programming languages. It is a dynamic object oriented language which can be easily used for software development. It supports many other programming languages and has extensive library support for many other languages.

34. Explain About The Use Of Python For Web Programming?

Python can be very well used for web programming and it also has some special features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, Web servers, Content Management systems, Web services, Web client programming, Web services, etc. Many high end applications can be created with Python because of the flexibility it offers.

35. State Some Programming Language Features Of Python?

Python supports many features and is used for cutting edge technology. Some of them are

1) A huge pool of data types such as lists, numbers and dictionaries.

2) Supports notable features such as classes and multiple inheritance.

3) Code can be split into modules and packages which assists in flexibility.

4) It has good support for raising and catching which assists in error handling.

5) Incompatible mixing of functions, strings, and numbers triggers an error which also helps in good programming practices.

6) It has some advanced features such as generators and list comprehensions.

7) This programming language has automatic memory management system which helps in greater memory management.

36. How Is Python Interpreted?

Python has an internal software mechanism which makes your programming easy. Program can run directly from the source code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.

37. Does Python Support Object Oriented Scripting?

Python supports object oriented programming as well as procedure oriented programming. It has features which make you to use the program code for many functions other than Python. It has useful objects when it comes to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.

38. Describe About The Libraries Of Python?

Python library is very huge and has some extensive libraries. These libraries help you do various things involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as Twisted, wx python, python imaging library, etc.

39. State And Explain About Strings?

Strings are almost used everywhere in python. When you use single and double quotes for a statement in python it preserves the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have created a string in Python you can never change it again.

40. Explain About Classes In Strings?

Classes are the main feature of any object oriented programming. When you use a class it creates a new type. Creating class is the same as in other programming languages but the syntax differs. Here we create an object or instance of the class followed by parenthesis.

41. What Is Tuple?

Tuples are similar to lists. They cannot be modified once they are declared. They are similar to strings. When items are defined in parenthesis separated by commas then

They are called as Tuples. Tuples are used in situations where the user cannot change the context or application; it puts a restriction on the user.

42. Explain and Statement about List?

As the name specifies list holds a list of data items in an orderly manner. Sequence of data items can be present in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be altered at any time.

43. Explain About The Dictionary Function In Python?

A dictionary is a place where you will find and store information on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that strings should be passed as keys in python. Notice that keys are to be separated by a colon and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.

44. Explain About Indexing And Slicing Operation In Sequences?

Tuples lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.

45. Explain About Raising Error Exceptions?

In python programmer can raise exceptions using the raise statement. When you are using exception statement you should also specify about error and exception object. This error should be related to the derived class of the Error. We can use this to specify about the length of the user name, password field, etc.

46. What Is A Lambda Form?

This lambda statement is used to create a new function which can be later used during the run time. Make repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in order to return them during the run time.

47. Explain About Assert Statement?

Assert statement is used to assert whether something is true or false. This statement is very useful when you want to check the items in the list for true or false function. This statement should be predefined because it interacts with the user and raises an error if something goes wrong.

48. Explain About Pickling And Unpicking?

Python has a standard module known as Pickle which enables you to store a specific object at some destination and then you can call the object back at later stage. While you are retrieving the object this process is known as unpicking. By specifying the dump function you can store the data into a specific file and this is known as pickling.

49. What Is The Difference Between A Tuple And A List?

A tuple is a list that is immutable. A list is mutable i.e. the members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.

Other significant difference is of the syntax. A list is defined as

list1 = [1, 2, 5, 8, 5, 3,]

list2 = ["Sachin", "Ramesh", "Tendulkar"]

A tuple is defined in the following way

tup1 = (1, 4, 2, 4, 6, 7, 8)

tup2 = ("Sachin","Ramesh", "Tendulkar")

50. If Given the First and Last Names of Bunch of Employees How Would You Store It and What Data type?

Either a dictionary or just a list with first and last names included in an element.

51. What Will Be the Output of the Following Code

Class C (object):

Def__init__(self):

Self.x =1

C=c()

Print C.x

Print C.x

Print C.x

Print C.x

All the outputs will be 1

1

1

1

1

52. What Is Python? What Are The Benefits Of Using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

53. How Python Can Be Used In Software Testing?

To generate test data; parse test results; generate reports; testing API calls etc.

Python to extract requirements from a Word document.

For testing tasks automation, setting up environments for tests, extracting performance data, etc…

Testers use Python extensively in many companies with Selenium for test automation.

For writing desktop applications used by testers.

Test data manipulation.

To build test environment

Testing with Iron Python on .NET

54. What Python Frameworks Do You Know?

Framework called Web2py, PAMIE (Python automation Module for I. E.), the py. Test framework

55. What Tools That Helps Python Development Do You Know?

There are good tools for helping Python development such as Notepad++ with the PyNPP plugin and Eclipse with PyDev and PyUnit

56. The Following Is Displayed By A Print Function Call: Yesterday Today Tomorrow Please Write An Example Of A Print Function?

Print (‘yesterdayntodayntomorrow’)

57. The Following Is Displayed By A Print Function Call?

Hello-how-are-you

58. Please Write An Example Of A Print Function?

Print (‘hello’ + ‘-‘+ ‘how’ + ‘-‘+ ‘are’ + ‘-‘ + ‘you’)

59. What Does the Expression Len (”) Evaluate To?

0

60. Considering the Following Code: S = ‘catandapple’ Write an Expression That Evaluate To ‘apple’?

S [-5:]

61. Write An Expression That Evaluate To True?

Len (‘aaddgg’) == 6

62. What Are “tuples”?

Tuples are immutable sequences: they cannot be modified. Tuples use parentheses instead of square brackets: tup = (‘test’, 5, -0.2)

63. What Are The Rules For Legal Python Names?

Names must start with a letter or _.

Names must contain only letters, digits, and _.

64. Which Command Do You Use To Exit Help Window Or Help Command Prompt?

Quit When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically

 

65. Does the Functions Help () And Dir () List The Names Of All The Built-in Functions And Variables? If No, How Would You List Them?

No. Built-in functions such as max (), min (), filter(), map(), etc is not apparent immediately as they are available as part of standard module. To view them, we can pass the module” built-ins ” as an argument to “dir()”. It will display the built-in functions, exceptions, and other objects as a list.>>>dir(__built-ins )

[‘Arithmetic Error’, ‘Assertion Error’, ‘Attribute Error’,]

66. Explain how Python Does Compile-time And Run-time Code Checking?

Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exists.

67. What is a “unit test” In Python?

The unit testing framework of Python is known as “unit test”.  It supports the sharing of setups, automation testing, shutdown code for tests, and aggregation of tests into collections, among others.

68. Define “slicing”?

“Slicing” is a mechanism to select a range of items from sequence types like list, tuple, strings etc.

69. What Are Generators In Python?

Generators are the means to implement integrators. It is a normal function except that it yields “expression” in the “function”.

70. Define “doctoring”?

“Doctoring” is a Python documentation string. It is the means to document Python “functions”, “modules” and “classes”.

71. How Do You Copy An Object In Python?

Copy. Copy () or copy.deepcopy ()

72. What is a “negative Index”?

Python sequences can be indexed as positive and negative numbers. For ac positive index, 0 is the first number, 1 is the second etc.  For a negative index, (-1) is the last index and (-2) is the second etc.

73. How Do You Convert A Number Into A String?

By using the inbuilt functions STR ().

74. What Is the Difference Between “xrange” And “range”?

“Xrange” returns the “Xrange” object while range returns the “list” irrespective of the size of the “range”.

75. Define “module” And “package”?

Each Python program file is a “module”, which imports other modules like “objects” and “attributes”.

A Python program folder is a “package” of “modules”.  A package can have “modules” or “subfolders”.

76. What Is Pep 8?

PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

77. What Is Pickling And Unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling.  While the process of retrieving original Python objects from the stored string representation is called unpickling.

78. How Python Is Interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

79. How Memory Is Managed In Python?

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by Python memory manager.  The core API gives access to some tools for the programmer to code.

Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

80. What Is Python? What Are The Benefits Of Using Python?

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

81. How Python Can Be Used In Software Testing?

To generate test data; parse test results; generate reports; testing API calls etc.

Python to extract requirements from a Word document.

For testing tasks automation, setting up environments for tests, extracting performance data, etc…

Testers use Python extensively in many companies with Selenium for test automation.

For writing desktop applications used by testers.

Test data manipulation.

To build test environment

Testing with Iron Python on .NET

82. What Python Frameworks Do You Know?

Framework called Web2py, PAMIE (Python automation Module for I. E.), and the py. Test framework

83. What Tools That Helps Python Development Do You Know?

There are good tools for helping Python development such as Notepad++ with the PyNPP plugin and Eclipse with PyDev and PyUnit

84. The Following Is Displayed By A Print Function Call: Yesterday Today Tomorrow Please Write An Example Of A Print Function?

Print (‘yesterdayntodayntomorrow’)

85. The Following Is Displayed By A Print Function Call?

Hello-how-are-you

86. Please Write An Example Of A Print Function?

Print (‘hello’ + ‘-‘+ ‘how’ + ‘-‘+ ‘are’ + ‘-‘+ ‘you’)

87. What Does the Expression Len (”) Evaluate To?

0

88. Considering the Following Code: S = ‘catandapple’ Write an Expression That Evaluate To ‘apple’?

S [-5:]

89. Write An Expression That Evaluate To True?

Len (‘aaddgg’) == 6

90. What Are “tuples”?

Tuples are immutable sequences: they cannot be modified. Tuples use parentheses instead of square brackets: tup = (‘test’, 5, -0.2)

91. What Are The Rules For Legal Python Names?

Names must start with a letter or _.

Names must contain only letters, digits, and _.

92. Which Command Do You Use To Exit Help Window Or Help Command Prompt?

Quit When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically

93. Does the Functions Help () and Dir () List the Names Of All The Built-in Functions And Variables? If No, How Would You List Them?

No. Built-in functions such as max (), min (), filter (), map (), etc is not apparent immediately as they are available as part of standard module. To view them, we can pass the module” built-ins” as an argument to “dir ()”. It will display the built-in functions, exceptions, and other objects as a list. >>>dir (__built-ins )

[‘Arithmetic Error’, ‘Assertion Error’, ‘Attribute Error’, ……… ]

94. Explain how Python Does Compile-time And Run-time Code Checking?

Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exists.

95. What is a “unittest” In Python?

The unit testing framework of Python is known as “unittest”.  It supports the sharing of setups, automation testing, shutdown code for tests, and aggregation of tests into collections, among others.

96. Define “slicing”?

“Slicing” is a mechanism to select a range of items from sequence types like list, tuple, strings etc.

97. What Are Generators In Python?

Generators are the means to implement integrators. It is a normal function except that it yields “expression” in the “function”.

98. Define “doctoring”?

“Docstring” is a Python documentation string. It is the means to document Python “functions”, “modules” and “classes”.

99. How Do You Copy An Object In Python?

Copy. Copy () or copy.deepcopy ()

100. What is A “negative Index”?

Python sequences can be indexed as positive and negative numbers. For ac positive index, 0 is the first number, 1 is the second etc.  For a negative index, (-1) is the last index and (-2) is the second etc.

101. How Do You Convert A Number Into A String?

By using the inbuilt functions str ().

102. What Is the Difference Between “xrange” And “range”?

“Xrange” returns the “Xrange” object while range returns the “list” irrespective of the size of the “range”.

103. Define “module” And “package”?

Each Python program file is a “module”, which imports other modules like “objects” and “attributes”.

A Python program folder is a “package” of “modules”.  A package can have “modules” or “subfolders”.

104. What Is Pep 8?

PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

105. What Is Pickling And Unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling.  While the process of retrieving original Python objects from the stored string representation is called unpickling.

106. How Python Is Interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

107. How Memory Is Managed In Python?

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by Python memory manager.  The core API gives access to some tools for the programmer to code.

Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

108. How Do I Build Wxpython On Unix?

This file describes how I build wxWidgets and wxPython while doing development and testing, and is meant to help other people that want to do the same thing. Those readers who have attempted this in previous releases of the software will probably notice that this file is much smaller than it was before. Much thanks for this goes to Kevin Ollivier who wrote the initial version of the new build scripts and then guilted me into starting to use and maintain them myself.

Building of both wxWidgets and wxPython is now handled by the wxPython/build-wxpython.py script in the source tree. It takes care of all the nasty and confusing details that used to be documented in this file. Pretty much all you need to worry about now is having the build tools and dependent libraries installed on your system and specifying where to install the results, if other than the standard location.

If you want to make changes to any of the *.i files, (SWIG interface definition files,) then you will need to use a special patched version of SWIG. Get the sources for version 1.3.29, and then apply the patches in wxPython/SWIG and then build SWIG like normal. See the README.txt in the wxPython/SWIG dir for details about each patch.

If you install this build of SWIG to a location that is not on the PATH (so it doesn't interfere with an existing SWIG install for example) then you can set a SWIG environment variable to the full path of this new binary to tell the build script which SWIG to use.

109. How Do I Build Wxpython On Windows?

The Windows builds currently require the use of Microsoft Visual C++. Theoretically, other compilers (such as mingw32 or the Borland compilers) can also be used but I've never done the work to make that happen. If you want to try that then first you'll want to find out if there are any tricks that have to be done to make Python extension modules using that compiler, and then make a few changes to setup.py to accommodate that. (And send the patches to me.) If you plan on using VisualStudio.Net (a.k.a. MSVC 7.1) keep in mind that you'll also have to build Python and any other extension modules that you use with that compiler because a different version of the C runtime library is used. The Python executable that comes from PythonLabs and the wxPython extensions that I distribute are built with MSVC 6 with all the Service Packs applied. This policy will change with Python 2.4 and MSVC 7.1 will be used starting with that version.

If you want to build a debuggable version of wxWidgets and wxPython you will need to have also built a debug version of Python and any other extension modules you need to use. You can tell if you have them already if there is a _d in the file names, for example python_d.exe or python23_d.dll. If you don't need to trace through the C/C++ parts of the code with the debugger then building the normal (or hybrid) version is fine, and you can use the regular python executables with it.

Starting with 2.5.3.0 wxPython can be built for either the monlithic or the multi-lib wxWidgets builds. (Monolithic means that all the core wxWidgets code is in one DLL, and multi-lib means that the core code is divided into multiple DLLs.) To select which

one to use specify the MONOLITHIC flag for both the wxWidgets build and the wxPython build as shown below, setting it to either 0 or 1.

Just like the unix versions I also use some scripts to help me build wxWidgets, but I use some non-standard stuff to do it. So if you have bash (cygwin or probably MSYS too) or 4NT plus unix-like cat and sed programs then there is a copy of my wxWidgets build scripts in %WXDIR%wxPythondistribmsw. Just copy them to %WXDIR%buildmsw and you can use them to do your build, otherwise you can do everything by hand as described below. But if you do work by hand and something doesn't seem to be working correctly please refer to the build scripts to see what may need to be done differently.

110. Python Crashes In Kernel32.dll When I Import Wxpython In Windows 95?

You can probably fix this by installing winsock2

111. I Don't Know C++, How Can I Use The Docs?

Apart from the "wxPython Notes" and some articles under "Topic Overview" which you may find useful, the most important parts of the wxPython documentation, for the Python programmer, are:

The Alphabetical Class Reference

The list of Functions

This is the information which you'll need to refer to again and again as you're developing your wxPython apps. Unfortunately, though, these references are written for C++ programmers, so virtually all the method and function definitions are in C++ format, which makes it hard for a Python programmer to make sense of.

112. I Ran "python Demo.py" And All I Got Was This: Traceback (most Recent Call Last): File "demo.py", Line 3, In ? Import Main File "main.py", Line 15, In ? From Wxpython.wx Import * Importerror: No Module Named Wxpython.wx When I Did A Search Of My Whole Python Directory, I Found No File Named Wxpython.wx.

In this context the dot means that it is looking for a module named wx located in a Python package named wxPython. Translated to the filesystem that means a directory named wxPython with a file named wx.py located within it. And an empty file named "init.py" to make this folder a package.

This error message means that the wxPython directory is not located in a directory that is in the PYTHONPATH. To check your path run this from within Python:

import sys

print sys.path

If the directory containing the wxPython directory is not there you either need to move wxPython or add the directory to PYTHONPATH. This can be done either in the environment, in a sitecustomize.py file (that is on the default path) on in the registry on Win32. See the Python docs for more details.

On Linux the wxPython RPM for Python 2 puts wxPython in /usr/local/lib/python2.0/site-packages since Python 2 was installed in /usr/local on my build system. If Python 2 is in /usr on your system then you'll want to move (or link) wxPython to /usr/lib/python2.0/site-packages.

On Win32 wxPython will install to the Python directory by default, which is automatically on the PYTHONPATH, so Python will be able to find the modules using the above syntax. If you installed somewhere else then you need to add that directory to the PYTHONPATH as described above.

113. Can I Use Wxpython Binaries With A Different Version Of Python?

In general, no. You need to use the same version of Python as the wxPython binary was built with. That is why the version is part of the filename.

114. I've Looked At Tkinter And At Wxpython. Why Would I Choose One Or The Other?

Installation: tkInter is a GUI toolkit that has been distributed widely with Python, and is readily available to everyone who is running Python. wxPython requires an additional install on top of the Python install. If it's just for your own machine, this isn't a big deal, but if you have a lot of people who need it, this could become a bit of a big deal.

Native Look and Feel: wxPython supports the native look and feel of the platform being used. tkInter has its own look and feel for some components, which doesn't match any standard platform.

Windows XP and Python 2.2.2: In Python 2.2.2 under Windows XP you need this additional step:

Put two files python.exe.manifest and pythonw.exe.manifest, both with the following contents:

 version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" />

in your Python installation directory (where respective .exe files reside). Next time you run your wxPython applications, they'll look like "normal" XP applications.

 

This may also affect other Python modules that use Windows display API.

If you are using py2exe to build a standalone Python executable, say FOO.EXE, you need to copy pythonw.exe.manifest into the directory where FOO.EXE is and name it FOO.EXE.manifest.

Wide Range of Available Widgets: wxPython has a much wider range of available widgets than does tkInter. There are additions available for tkInter that somewhat mitigate this situation, but this destroys the convenience argument for tkInter. In addition, the wxPython toolkit has support for printing and other non-GUI, but also non-standard operations. tkInter is fine if your application is simply a way of interacting with the user via a GUI, but if you need to develop a full-scale application with support for drawing your own UI elements, support for printing, etc., wxPython is definitely the way to go.

115. Is There A Mailing List For Help?

Yes. You can subscribe to the list, and read the archives.

116. How Do I Get Help From The Wxpython-users Mailing List?

When you have a unique problem, it is time to ask a  on wxPython-users. Please conform to the basic rules of netiquet. Aside from them, there is one thing you can do to improve your chances of getting a helpful answer if you have some idea how to do something, but it's not quite working:

Send a Complete, Working App that demonstrates your problem or . This app should be complete, in that it can be run, but as small as possible, so that it isolates your problem, and gives those of us that read the list as little to look at as possible.

This accomplishes two things:

When isolating your problem, you might just find out why it wasn't working.

It makes it MUCH easier for us to help you, for a number of reasons:

We can just run the app and see how it's behaving.

We can easily tweak it, and try to find a solution.

Your problem may not be where you think it is. If you don't send a complete version, your problem may not be in the code you send, or be a function of how that code is used.

117. What Is The Difference Between A Wxframe And A Wxwindow? When Do I Want To Use Each One?

The terminology is a bit confusing. a wxFrame is what most folks think of as a Window: a box on the screen that holds your application, etc. It can be re-sized, moved, etc with the mouse by the window manager of the system.

A wxWindow is the basic unit from which all the controls, etc. are built. It is a rectangle on the screen that captures mouse clicks, draws itself etc. a wxWindow will almost always be put into a Frame or other window.

You want to use a frame to create an independent box on the screen to house some part of your application. You want to use a wxWindow as the basis for a custom control of your own design. All the built-in controls are derived from a wxWindow already.

118. How Do I Use Multiple Threads?

All calls to methods of GUI objects and event handlers need to happen on the main thread. In wxPython the main thread is the one that first imports the wxPython.wx module. Other threads can send events to the main thread using wxPostEvent as is done in the Threads sample in the wxPython demo.

119. How Are Multiple Evt_xxx Calls Handled?

I am wondering about how EVT_XXX handles multiple calls. I want to change

how events are handled depending upon which mode my program is in. If I call

EVT_XXX multiple times for the same event, each time pointing to a different

method, are these event handlers chained or do subsequent calls replace the

old event handler?

Each instance of a class derived from wxEvt

Handler has a static event table, which is used only by C++ code, and a dynamic event table (just a list really) which is what wxPython uses although a few C++ developers use it too. Every time you call a EVT_XXX function it adds an entry to this list. When an event happens the first matching handler in the event table is called, and if it calls event.Skip() then the search continues so if another match is found then it is called too. The EVT_XXX functions are really just convenience wrappers around the wxEvt

Handler.Connect method. There is also a .Disconnect method that you can call if needed to remove an event handler binding.

120. How Can I Use A Visual Debugger With Wxpython ?

Most Debuggers (like IDLE or Python Win) use a different GUI toolkit than wxPython does, and some debug the wxPython app within their own process. This creates lots of conflicts between the wxPython event loop and the event loop of the debuggers' GUI tookit.

So, you need a debugger that debugs your program out-of-process. At present, HAP, Wing IDE and Komodo do so. HAP is open-source, so you might be interested in checking that one out;

121. How Do I Remove A Component, Or All Components Of A Certain Type From A Wxframe/wxpanel?

If your container is using a sizer, you can remove all its children with this function:

Toggle line numbers

def removeChildren(self, destroy=1):

       """

Remove all my children components and optionally

destroy them.

    """

while self.GetSizer().Remove(0):

 pass

if destroy:

self.DestroyChildren()

To only remove children of a particular kind (ie.wxStaticText), you could add a parameter to the method, and do an isinstance() test.

122. How Do I Get A Wxgrid To Update Its Scrollbars?

In wxPython 2.4.0.2, wxGrid apparently does not update its scroll bars in response to changes in the rows and columns. You can cause it to do this by callingFitInside() on the wxGrid object.

123. How Do I Hide The Row And Column Labels In A Wxgrid Window?

Set the size to 0. The label windows will still exist, but they will not be visible.

grid.SetRowLabelSize(0)

grid.SetColLabelSize(0)

(thanks PaulMcNett for the info)

124. What's The Difference Between All The Dc Types?

wxPaintDC can only be used inside a EVT_PAINT event and has extra info about what regions of the window have been damaged and need to be refreshed, allowing some optimization of the re-draw. You can also use this information to optimize your redraw if you want.

wxClientDC can be used anytime for drawing to the window, but you must ensure that whatever you draw then is also redrawn in a EVT_PAINT event otherwise it will get lost the next time the window is refreshed. This is useful if you want to update the screen as a result of some other action, and can be used to display animations, etc.

wxMemoryDC allows you to draw to a wxBitmap instead of to a window. The resulting wxBitmap can be used for a variety of things, including an off screen buffer of what is on screen.

wxBufferedDC and wxBufferedPaintDC are simple convenience classes that derive from wxMemoryDC. You give it a buffer bitmap and then all drawing goes to the bitmap. When the last reference to the buffered dc goes out of scope or is deleted then the contents of the bitmap are dumped to the real DC (if any) that you gave to the buffered dc when you constructed it. This helps to reduce flicker and such for complex drawings. and also reduces the time needed for EVT_PAINT handlers because all they are doing is drawing the buffer bitmap, not a whole complex drawing. You can easily do the same thing yourself without the buffered DCs with just a wxMemoryDC, a bitmap and a DrawBitmap call.

125. Why Doesn't The Getstring Method Of Wxcommandevent Work?

Many simple controls like buttons, list boxes, check boxes, etc., generate a wxCommandEvent, because the event is often processed by the parent window, and only command events propogate to the parent (if the control itself doesn't handle them). However, because the values needed by the event handler vary depending on the type of the control and on the specific event, wxCommandEvent has a variety of different methods for retrieving the value. Depending on the control and event, not all these methods will return non-zero or non-empty values. For example, GetString only works for EVT_LISTBOX and EVT_CHOICE, but doesn't make any sense for EVT_CHECKBOX. Read the documentation of the wxCommandEvent method for details of which events support that method. If you need additional information, you'll need to retrieve a reference to the control which generated the event (see How can my EVT_XYZ handler find the control that generated an event?)

126. Why Do The Paths To My Resource Files Work In Testing, But Fail After Installation On Windows?

This is a known problem. In testing, the relative paths point to the files correctly, but after installation the relative paths do not point to the intended location. To remedy this, you will need to provide a dynamic absolute path to the resource files.

Insert the following code in your main Python file:

import sys

import os.path

import __builtin__

# Sets the homepath variable (you can change the name) to the directory where your application is located (sys.argv[0]).

__builtin__.__dict__['homepath'] = os.path.abspath(os.path.dirname(sys.argv[0]))

Whenever you need to load a resource file, you have to append homepath as follows, using os.path.join(). Your application will now load directory names correctly in both testing and post-installation.

toolbar.AddSimpleTool(1, wx.Image(os.path.join(homepath, 'resfilenew.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '')

127. How Can My Evt_xyz Handler Find The Control That Generated An Event?

The event your handler receives will be of a class derived from wxEvent, which has a GetEventObject method. In the case of an event generated by a control, calling GetEventObject() on the event will return a reference to the control.

128. How Do I Embed Images In Python Code?

Use img2py.py from the tools folder of your wxPython installation. It converts an image file to .png format, compresses it, and stores the binary data in a .py file with routines to load the image.

129. How Do I Keep Wxpython From Redirecting Errors And Exceptions To A Gui Window?

Quoting from Getting Started

When a python program hits an unhandled exception (bug!) in your program, it aborts with a traceback that is useful in locating the source of the problem. wxPython programs do the same, but with a twist. The traceback is routed to stdio, which is captured in a nice GUI frame independent of your program. If an exception shows up in an event handler, the traceback is displayed, and your program continues on as best it can. BUT, if the exception occurs while initializing your program, the traceback will show up, and then your program will abort, taking the stdio window (and your traceback) with it before even the fastest reader can make sense of it.

You can keep stdio from being hijacked by wxPython by providing a couple of optional parameters when you instantiate your wxApp. An example says it best:

Toggle line numbers

myapp = MyApp() # functions normally. Stdio is redirected to its own window

myapp = MyApp(0) #does not redirect stdout. Tracebacks will show up at the console.

myapp = MyApp(1, 'filespec') #redirects stdout to the file 'filespec'

# NOTE: These are named parameters, so you can do this for improved readability:

myapp = MyApp(redirect = 1, filename = 'filespec') # will redirect stdout to 'filespec'

myapp = MyApp(redirect = 0) #stdio will stay at the console...

130. I Created A Sample Application With Some Controls But When I Reach The Last Control And Hit The Tab Key Again Focus Does Not Return To The First Control. What Is Wrong?

Maybe you are using the wxNotebook window. If you place a wxNotebook directly on a frame tab order usually gets confused. Try placing a wxPanel on the wxFrame and put wxNotebook onto this panel. As a rule, simply do not place wxNotebook directly on a wxFrame (except the frame is a wxDialog?). If you use a

WxDialog, tabbing should work as expected. If you use a MDIChildFrame, you must create a Panel first, and then put your controls on the Panel, not directly on the MDIChildFrame.

131. What Does "unicode Build" Really Mean?

Unicode in Python: There are a few aspects of unicode-ness to keep track of here. First, in Python there are unicode objects and there are string objects. String objects are essentially a sequence of 8-bit characters, and unicode objects are a sequence of "wide" characters (either 16-bit or 32-bit depending on platform and options used when building Python.) They are related to each other in that a unicode object can be

encoded into a string object using a specific "codec" (a matched enCODer and DECoder pair). You can think of a codec as being like the "magic decoder ring" that came in the box of cereal when you were a kid, (or perhaps when your dad was a kid...) String objects can be decoded into a unicode object using the decoder part of the codec.

Unicode in wxWidgets: On the other side of the fence is wxWidgets and how it can use unicode. In the C++ code there is a class named wxString, and all string type parameters and return values in the wxWidgets library use a wxString type. The wxWidgets library has a unicode compile switch that makes wxString be either an array of 8-bit characters (the C char data type) or an array of wide characters (C's wchar_t data type.) So in other words you can have a wxWidgets build where wxStrings are unicode and another build where wxStrings are ansi strings.

Unicode in wxPython: So what does all that mean for wxPython? Since Python does know about string and unicode objects, and you can have both in the same program, the wxPython wrappers need to attempt to do something intelligent based on if the wxWidgets being used is an unicode build or an ansi build.

So, if wxPython is using an ansi build of wxWidgets then:

Return values from wx functions and methods will be string objects.

Strings passed as parameters to wx functions and methods will be used without conversion.

Unicode objects passed as parameters to wx functions and methods will first be converted to a string object using the default encoding. You can use sys.getdefaultencoding() to find out what the default encoding is. You may get an UnicodeEncodeError if there are characters in the unicode object which don't have a matching ordinal in the default encoding. To work around this you can convert the unicode object to a string yourself using a different codec.

And if wxPython is using an unicode build of wxWidgets then:

Return values from wx functions and methods will be unicode objects.

Strings passed as parameters to wx functions and methods will first be converted to a unicode object using the default encoding. You may get an UnicodeDecodeError exception if there are characters in the string that are not mapped to unicode ordinals by the default encoding. To work around this you can convert the string to unicode yourself using a specific codec.

Unicode objects passed as parameters to wx functions and methods will be used without conversion.

132. What Is A Wxpython Release Series?

The wxWidgets project has adopted the release model used by the Linux Kernel project where there are alternating sets of releases where one set are considered "stable" and the next set are considered "development." For wxWidgets "stable" and "development" do not refer to bugginess, but to the stability of the API and backwards compatibility.

Stable: For the duration of the series existing APIs are not modified, although new non-virtual class methods and such can be added. Binary compatibility of the C++ libs is maintained by not allowing any changes that modify the in-memory size or layout of the classes and structs. This can and often does impose limitations on what kinds of enhancements or bug fixes can be performed in a stable release series, however this really only affects the C++ layer because in Python being backwards compatible has a slightly different connotations.

Development: The main purpose of the development series of releases is to add new functionality or to correct problems that could not be corrected in a stable series because of binary compatibility issues, all in an effort to create the next stable series. So for the duration of the development series existing the APIs are allowed to be modified or removed as needed, although most of the time C++ source-level compatibility is maintained via deprecated overloaded functions or macros, etc. For wxPython this often means that there will be source-level incompatibilities because there is no overloading or macros, and in order to support the new version of the API sometimes the old version has to be removed.

Because of the binary compatibility issues, the latest development version of wxWidgets/wxPython can often be less buggy than the latest version of the last stable release series. However there is the trade-off that the APIs may be changing or evolving between versions in the development series.

133. How Do The Version Numbers Work?

For releases wxPython uses a 4 component version number. While this looks a lot like how version numbers are used in other Open Source projects, there are a few subtle differences. So for some release A.B.C.D you can deduce the following:

1. Release Series: The first two components of the version number (A.B) represent the release series, and if the B component is an even number then it is a stable series, if it is an odd number then it is an development release series. For example, 2.4, 2.6, and 2.8 are stable and the API is more or less frozen within each series, and 2.3, 2.5, and 2.7 are development and the API and functionality is allowed to change or evolve as needed.

Because of this there can be quite large changes between one stable series to the next (say 2.4 to 2.6) and this often throws people off because in other projects changes of that magnitute would have caused the first component of the version number to change. Instead you should think of the combination of A.B as being the major number of the version.

2. Release Number: The third component of the version number (C) represents one of the releases in a release series. For example, 2.5.0, 2.5.1, 2.5.2, 2.5.3... are all releases in the 2.5 release series. (And since in this case it is an development series then the API and functionality of 2.5.3 has evolved to be different in places than it was in 2.5.0.) The C++ wxWidgets releases usually stop here and only A.B.C releases are made.

3. Subrelease number, or wxPython release: The fourth component of the version number (D) is used to represent a subrelease, or incremental releases betweeen the official wxWidgets releases. These releases include fixes for wxWidgets bugs that wxPython may have exposed, or minor enhancements that are important for wxPython. This is not an arbitrary wxWidgets snapshot, but rather a tested version of the code with fixes and enhancements not yet available from wxWidgets except from the source code repository.

It can sometimes be confusing to keep track of the various size-related attributes of a wx.Window, how they relate to each other, and how they interact with sizers. This document will attempt to clear the fog a little, and give some simple explanations of things.

BestSize: The best size of a widget depends on what kind of widget it is, and usually also on the contents of the widget. For example a wx.ListBox's best size will be calculated based on how many items it has, up to a certain limit, or a wx.Button's best size will be calculated based on its label size, but normally won't be smaller than the platform default button size (unless a style flag overrides that). Get the picture? There is a special method in the C++ code called DoGetBestSize() that a class needs to override if it wants to calculate its own best size based on its content. The default DoGetBestSize() is designed for use in container windows, such as wx.Panel, and works something like this:

if the window has a sizer then it is used to calculate the best size.

if the window has layout constraints then that is used to calculate the best size.

if the window has children then the best size is set to be large enough to show all the children.

if there are no children then the window's min size will be used for the best size.

if there is no min size, then the current size is used for the best size.

MinSize: The min size of a widget is a size that is normally explicitly set by the programmer either with the SetMinSize() method or the SetSizeHints() method. Most controls will also set the min size to the size given in the control's constructor if a non-default value is passed. Top-level windows such as wx.Frame will not allow the user to resize the frame below the min size.

Size: The size of a widget can be explicitly set or fetched with the SetSize() or GetSize() methods. This size value is the size that the widget is currently using on screen and is the way to change the size of something that is not being managed by a sizer.

ClientSize: The client size represents the widget's area inside of any borders belonging to the widget and is the area that can be drawn upon in a EVT_PAINT event. If a widget doesn't have a border then its client size is the same as its size.

Initial size: The initial size of a widget is the size given to the constructor of the widget, if any. As mentioned above most controls will also set this size value as the control's min size. If the size passed to the constructor is the default wx.DefaultSize, or if the size is not fully specified (such as "size=(150,-1)") then most controls will fill in the size using the best size and will set the initial size of the control to the resulting size.

AdjustedBestSize: This value is calculated by taking the max of the widget's best size and min size values and returning the result. This has been removed in 2.7.2.

GetEffectiveMinSize: (formerly GetBestFittingSize) A blending of the widget's min size and best size, giving precedence to the min size. For example, if a widget's min size is set to (150, -1) and the best size is (80, 22) then the best fitting size is (150, 22). If the minsize is (50, 20) then the best fitting size is (50, 20). This method is what is called by the sizers when determining what the requirements of each item in the sizer is, and is used for calculating the overall minimum needs of the sizer.

SetInitialSize(size): (formerly SetBestFittingSize) This is a little different than the typical size setters. Rather than just setting an "initial size" attribute it actually sets the minsize to the value passed in, blends that value with the best size, and then sets the size of the widget to be the result. So you can consider this method to be a "Smart SetSize". This method is what is called by the constructor of most controls to set the minsize and initial size of the control.

window.Fit(): The Fit method sets the size of a window to fit around its children. If it has no children then nothing is done, if it does have children then the size of the window is set to the window's best size.

sizer.Fit(window): This sets the size of the window to be large enough to accommodate the minimum size needed by the sizer, (along with a few other constraints...) If the sizer is the one that is assigned to the window then this should be equivalent to window.Fit().

sizer.Layout(): Recalculates the minimum space needed by each item in the sizer, and then lays out the items within the space currently allotted to the sizer.

window.Layout(): If the window has a sizer then it sets the space given to the sizer to the current size of the window, which results in a call to sizer.Layout(). If the window has layout constraints instead of a sizer then the constraints algorithm is run. The Layout method is what is called by the default EVT_SIZE handler for container windows.

134. Why Can't I Globally Catch Exceptions From Mainloop?

One of the often asked s for wxPython has to do with why you can't use a global exception handler wrapped around the call to the app object's MainLoop method. To understand the answer to this  you need to keep in mind that wxWidgets and the wxPython wrappers are C++ code and whenever an event handler or other callback is called you end up with another layer of C++ and Python code on the stack. I usually refer to this as the C++/Python sandwich. For example:

You call MainLoop: this is a Python to C++ transition.

The user clicks a button and your EVT_BUTTON handler is called, which transitions back to Python

The handler calls self.SetSize, now we are back in C++

You have a EVT_SIZE handler that is called, which puts us back in Python

The handler calls Layout(), back in C++

The Layout causes some other panel to get resized, and it has it's own EVT_SIZE handler, now we're back in Python again.

That EVT_SIZE handler calls Update to force an immediate repaint of the panel, putting us back in C++

The handler for the EVT_PAINT is called, which puts control on the Python side once more.

135. Why Doesn't A Sizer On A Wx.window Work?

probably a little surprising to find out that it doesn't work at all. No layout happens. It's as if the sizer isn't there at all. There is a good reason for this, and there is also a very simple workaround.

The reason is that since wx.Window is the base of the window hierarchy then adding auto-layout support to wx.Window would mean that every widget would inherit it, even those that are not intended to be containers of other windows. For example it doesn't make much sense to have wx.CheckBox support auto-layout functionality because it will likely never have child widgets that it needs to manage.

The workaround is very simple, just use a wx.Panel instead of a wx.Window. If for some reason you do want to use a wx.Window and also give it a sizer, then simply bind a handler for EVT_SIZE to the window too, and in the event handler call self.Layout().

136. What is the difference between deep and shallow copy?

Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

137. What is the difference between list and tuples?

Ans: Lists are mutable i.e they can be edited. Syntax: list_1 = [10, ‘Chelsea’, 20]

Tuples are immutable (tuples are lists which can’t be edited). Syntax: tup_1 = (10, ‘Chelsea’ , 20)

138. How is Multithreading achieved in Python?

Ans: 

Python has a multi-threading package but if you want to multi-thread to speed your code up.

Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.

This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.

All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

139. How can the ternary operators be used in python?

Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

Syntax:

The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

GET STARTED WITH PYTHON

140. How is memory managed in Python?

Ans: 

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap. 

The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.

Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

141. Explain Inheritance in Python with an example.

Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

Single Inheritance – where a derived class acquires the members of a single super class.

Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2.

Hierarchical inheritance – from one base class you can inherit any number of child classes

Multiple inheritance – a derived class is inherited from more than one base class.

142. Explain what Flask is and its benefits?

Ans: Flask is a web micro framework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is little dependency to update and less security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

143. What is the usage of help() and dir() function in Python?

Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. 

Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.

Dir() function: The dir() function is used to display the defined symbols.

144. Whenever Python exits, why isn’t all the memory de-allocated?

Ans: 

Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.

It is impossible to de-allocate those portions of memory that are reserved by the C library.

On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.

145. What is dictionary in Python?

Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

Let’s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.

1

dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

1

print dict[Country]

India

1

print dict[Capital]

Delhi

1

print dict[PM]

Modi

146. What is monkey patching in Python?

Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

Consider the below example:

1

2

3

4

# m.py

class MyClass:

def f(self):

print "f()"

We can then run the monkey-patch testing like this:

1

2

3

4

5

6

7

import m

def monkey_f(self):

print "monkey_f()"

 

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

The output will be as below:

monkey_f()

As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.

147. What does this mean: *args, **kwargs? And why would we use it?

Ans: We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargsis used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use*bob and **billy but that would not be wise.

148. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.

Ans:  Let us first write a multiple line solution and then convert it to one liner code.

1

2

3

4

5

6

with open(SOME_LARGE_FILE) as fh:

count = 0

text = fh.read()

for character in text:

    if character.isupper():

count += 1

We will now try to transform this into a single line.

1

count sum(1 for line in fh for character in line if character.isupper())

149. What are negative indexes and why are they used?

Ans: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

150. How can you randomize the items of a list in place in Python?

Ans: Consider the example shown below:

1

2

3

4

from random import shuffle

x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']

shuffle(x)

print(x)

The output of the following code is as below.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

151. What is the process of compilation and linking in python?

Ans: The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that is required in this as:

Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp

Place this file in the Modules/ directory of the distribution which is getting used.

Add a line in the file Setup.local that is present in the Modules/ directory.

Run the file using spam file.o

After successful run of this rebuild the interpreter by using the make command on the top-level directory.

If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

152. Write a sorting algorithm for a numerical dataset in Python.

Ans: The following code can be used to sort a list in Python:

1

2

3

4

list = ["1", "4", "0", "6", "9"]

list = [int(i) for i in list]

list.sort()

print (list)

153. Looking at the below code, write down the final values of A0, A1, …An.

1

2

3

4

5

6

7

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))

A1 = range(10)A2 = sorted([i for i in A1 if i in A0])

A3 = sorted([A0[s] for s in A0])

A4 = [i for i in A1 if i in A3]

A5 = {i:i*i for i in A1}

A6 = [[i,i*i] for i in A1]

print(A0,A1,A2,A3,A4,A5,A6)

Ans: The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary

A1 = range(0, 10)

A2 = []

A3 = [1, 2, 3, 4, 5]

A4 = [1, 2, 3, 4, 5]

A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

154. Explain split(), sub(), subn() methods of “re” module in Python.

Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:

split() – uses a regex pattern to “split” a given string into a list.

sub() – finds all substrings where the regex pattern matches and then replace them with a different string

subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

155. How can you generate random numbers in Python?

Ans: Random module is the standard module that is used to generate the random number. The method is defined as:

1

2

import random

random.random

The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates the random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates different instance of individual threads. The other random generators that are used in this are:

randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.

uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number

normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.

The Random class that is used and instantiated creates an independent multiple random number generators.

156. What is the difference between range & xrange?

Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

157. What is pickling and unpickling?

Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

Django – Python Interview s

158. Mention the differences between Django, Pyramid and Flask.

Ans: 

Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.

Django can also used for larger applications just like Pyramid. It includes an ORM.

159. Discuss the Django architecture.

Ans: Django MVT Pattern:

Figure:  Python Interview s – Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

160. Explain how you can set up the Database in Django.

Ans: You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.

Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on

Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.

If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.

Django uses SQLite as default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.

We will add the following lines of code to the setting.py file:

1

2

3

4

5

6

DATABASES = {

     'default': {

          'ENGINE' : 'django.db.backends.sqlite3',

          'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),

     }

}

GET PYTHON CERTIFIED TODAY

161. Give an example how you can write a VIEW in Django?

Ans: This is how we can use write a view in Django:

1

2

3

4

5

6

7

from django.http import HttpResponse

import datetime

 

def Current_datetime(request):

     now = datetime.datetime.now()

     html = "<html><body>It is now %s</body></html>" % now

     return HttpResponse(html)

Returns the current date and time, as an HTML document