Top Banner

of 20

python interview q & A

Jul 07, 2018

Download

Documents

satya_sap
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/18/2019 python interview q & A

    1/20

     hat are the ways to write a function using

    call by reference?

    Arguments in python are passed as an assignment. This assignment creates an object that has no relationship

     between an argument name in source and target. The procedure to write the function using call by reference

    includes:

    The tuple result can be returned to the object which called it. The example below shows it:

    def function(a, b):

    a = !alue

     b = b " #

    $ a and b are local !ariables that are used to assign the new objectsreturn a, b

    $ This is the function that is used to return the !alue stored in b

    % The use of global !ariables allows the function to be called as reference but this is not the safe method to call

    any function.

    % The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the

    function by reference.

    def function(a):

    a&' = string

    a = a " #

    $ The ‘a’ array gi!e reference to the mutable list and it changes the changes that are shared

    args = &string, #'

    func#(args)

     print args&', args

    $This prints the !alue stored in the array of ‘a’

     hat are the commands that are used to copy an

    object in Python?

    The command that is used to copy an object in python includes:

    % copy.copy() function: This maes a copy of the file from source to destination. *t returns a shallow copy of

    the parameter that is passed.

    % copy.deepcopy(): This also creates a copy of the object from source to destination. *t returns a deep copy of

    the parameter that is passed to the function.

    The dictionary consists of all the objects and the copy() method which is used as:

    newdict = olddict.copy()

  • 8/18/2019 python interview q & A

    2/20

    The assignment statement doesn’t copy any object but it creates a binding between the target and the object

    that is used for the mutable items. +opy is reuired to eep a copy of it using the modules that is pro!ided to

    gi!e generic and shallow operations.

     hat is the difference between deep and shallow

    copy?

    % -hallow copy is used when a new instance type gets created and it eeps the !alues that are copied in the

    new instance. hereas, deep copy is used to store the !alues that are already copied.

    % -hallow copy is used to copy the reference pointers just lie it copies the !alues. 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.

    hereas, deep copy doesn’t copy the reference pointers to the objects. /eep copy maes 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.

    % -hallow copy allows faster execution of the program and it depends on the si0e of the data that is used.

    hereas, deep copy maes it slower due to maing certain copies for each object that is been called.

     rite a program to find out the name of an

    object in python.

    The object doesn’t ha!e any name and there is no way the can be found out for objects. The assignment is

    used to bind a name to the !alue that includes the name of the object that has to be bound by a !alue. *f the

    !alue is callable then the statements are made true and then the program followed can be used to find the

    reference name of an object.

    class try:

     pass

    1 = A

    a = 1()

     b = a print b

    233main33.try instance at 'x#4/'5++6

     print b

    The class consists of name and the names are in!oed by using the the !ariable 1 that creates an instance for

    the class try. The method is to find out from all the namespaces that the object exists and then print the name

    of the object.

    How can the ternary operators be used in

  • 8/18/2019 python interview q & A

    3/20

    python?

    The ternary operator is the operator that is used to show the conditional statements. This consists of the true orfalse !alues with a statement that has to be e!aluated for it. The operator will be gi!en as:

    &on3true if &expression else &on3false

    x, y = 78, 8'

     big = x if x 2 y else y

    This is the lowest priority operator that is used in maing a decision that is based on the !alues of true or false.

    The expression gets e!aluated lie if x2y else y, in this case if x2y is true then the !alue is returned as big=x

    and if it is incorrect then big=y will be sent as a result.

    How the string does get converted to a number?

    % To con!ert the string into a number the built%in functions are used lie int() constructor. *t is a data type that

    is used lie int (‘#’) ==#.

    % float() is also used to show the number in the format as float(‘#’)=#.

    % The number by default are interpreted as decimal and if it is represented by int(‘'x#’) then it gi!es an

    error as 9aluerror. *n this the int(string,base) function taes the parameter to con!ert string to number in this

    the process will be lie int(‘'x#’,#4)==#4. *f the base parameter is defined as ' then it is indicated by an

    octal and 'x indicates it as hexadecimal number.% There is function e!al() that can be used to con!ert string into number but it is a bit slower and present many

    security riss lie 33import33(os).system(;rm %rf?;) % use of this will delete the home directory of the

    system.

     hat is the function of negative index?

    The seuences in python are indexed and it consists of the positi!e as well as negati!e numbers. The numbers

    that are positi!e uses ‘'’ that is uses as first index and ‘#’ as the second index and the process goes on

    lie that. The index for the negati!e number starts from ‘%#’ that represents the last index in the seuence

    and ‘%7’ as the penultimate index and the seuence carries forward lie the positi!e number. The negati!e

    index is used to remo!e any new%line spaces from the string and allow the string to except the last character

    that is gi!en as -&:%#. The negati!e index is also used to show the index to represent the string in correct

    order.

     rite a program to chec whether the object is

    of a class or its subclass.

  • 8/18/2019 python interview q & A

    4/20

    There is a method which is built%in to show the instances of an object that consists of many classes by

     pro!iding a tuple in a table instead of indi!idual classes. The method is gi!en as isinstance(obj,cls) and in

    more details gi!en as:

    isinstance(obj, (class#, class7, ...)) that is used to chec about the object’s presence in one of the classes. The built in types can also ha!e many formats of the same function lie isinstance(obj, str) or isinstance(obj, (int,

    long, float, complex)).

    *t is not preferred to use the class instead user%defined classes are made that allow easy object%oriented style to

    define the beha!ior of the object’s class. These perform different thing that is based on the class. The

    function differs from one class to another class.

    To find out the object of the particular class the following program is used:

    def search(obj):

    if isinstance(obj, box):$ This is the code that is gi!en for the box and write the program in the object

    elif isinstance(obj, /ocument):

    $ This is the code that searches the document and writes the !alues in it

    elif

    obj.search()

    $This is the function used to search the object’s class.

     hy does delegation performed in Python?

    /elegation is a techniue that is used in object oriented programming. This is used to show the object and the

     beha!ior of the methods that are used. The class can be created to pro!ide an implementation of the method

    that allows the method to be referenced. The delegate is ha!ing the parameter and the return !alue in an object.

    *t also allows the methods to be passed as parameters and allow the defining of the callbac methods that can

     be grouped together in multiple methods. These methods can be called from a single e!ent. The example

    shows a class that captures the beha!ior of the file and con!erts data from lower to uppercase.

    class upcase:

    def 33init33(self, out):self.3out = out

    def write(self, s):

    self.3outfile.write(s.upper())

    def 33getattr33(self, name):

    return getattr(self.3out, name)

    The write() method that is used in the upcase class con!erts the string to the uppercase before calling another

    method. The delegation is being gi!en using the self.33outfile object.

     hat is the function of !self"?

  • 8/18/2019 python interview q & A

    5/20

    !-elf " is a !ariable that represent the instance of the object to itself. *n most of the object oriented programming language, this is passed as to the methods as a hidden parameters that is defined by an object.

    1ut, in python it is declare it and pass it explicitly. *t is the first argument that gets created in the instance of

    the class A and the parameters to the methods are passed automatically. *t refers to separate instance of the

    !ariable for indi!idual objects. This is the first argument that is used in the class instance and the !self " 

    method is defined explicitly to all the methods that are used and present. The !ariables are referred as

    !self.xxx".

    How is !self" explicitly defined in a method?

    @-elf is a reference !ariable and an instance attribute that is used instead of the local !ariable inside the class.

    The function or the !ariable of the self lie self.x or self.meth() can be used in case the class is not nown.

    There are no !ariables declared as local. *t doesnBt ha!e any syntax and it allow the reference to be passed

    explicity or call the method for the class that is in use. The use of writebaseclass.methodname(self, 2argumentlist6) shows that the method of 3init3() can be extended to the base class methods. This also sol!es the

     problem that is syntactic by using the assignment and the local !ariables. This tells a way to the interpreter the

    !alues that are to be used for the instance !ariables and local !ariables. The use of explicit self.!ar sol!es the

     problem mentioned abo!e.

     hat is the use of join#$ for a string rather

    than list or tuple method?

    The functions and the methods that are used for the functionality uses the string module. This string module is

    represented as by using the join function in it:

    ;, ;.join(&#, 7, C, D, #4) that results in ;#, 7, C, D, #4;

    The string !ariable that is used pro!ide a fixed string literal to allow the names that are used to be bounded to

    the strings. join() is a string method that is used to pro!ide a separator string to use the function o!er the

    seuence of the string and insert the function to an adjacent elements. The method uses any number of

    arguments that follow some rules that has to be put up for the seuence objects that the class defines for itself.

    The join is used for the string module that is used to join the string characters together as it is gi!en in the program. The example is gi!en as:

  • 8/18/2019 python interview q & A

    6/20

    string.join(&#, 7, C, D, #4, ;, ;)

     hat is the process of compilation and lining

    in python?

    The compiling and lining allows the new extensions to be compiled properly without any error and the

    lining can be done only when it passes the compiled procedure. *f the dynamic loading is used then it

    depends on the style that is being pro!ided with the system. The python interpreter can be used to pro!ide the

    dynamic loading of the configuration setup files and will rebuild the interpreter.

    The steps that is required in this as:

    % +reate a file with any name and in any lanugage that is supported by the compiler of your system. Eor

    example comp.c

    % Flace this file in the ?odulesG directory of the distribution which is getting used.

    % Add a line in the file -etup.local that is present in the ?odulesG directory.

    % Hun the file using spam comp.o

    % After successful run of this rebuild the interpreter by using the mae command on the top%le!el directory.

    % *f the file is changed then run rebuild?aefile by using the command as Imae ?aefileB.

     hat is the procedure to extract values from

    the object used in python?

    To extract the !alue it reuires the object type to be defined and according to the object type only the !alues

    will be fetched.

    The values will be extracted as:

    % *f the object is a tuple then FyTuple3-i0e() method is used that returns the length of the !alues and another

    method FyTuple3Jet*tem() returns the data item that is stored at a specific index.

    % *f the object is a list then FyKist-i0e() is ha!ing the same function that is defined for the tuple and

    FyKist3Jet*tem() that also return the data items at a specified index.

    % -trings uses Fy-tring3-i0e() to return the length of the !alue and Fy-tring3As-tring() that return the pointer

    to its !alue.

    % To chec the type of the object and the extracted !alues use of methods lie Fy-tring3+hec(),

    FyTuple3+hec(), FyKist3+hec(), etc are used.

     hat are the steps re%uired to mae a script

    executable on &nix?

    The steps that are required to make a script executable are to:

  • 8/18/2019 python interview q & A

    7/20

    % Eirst create a script file and write the code that has to be executed in it.

    % ?ae the file mode as executable by maing the first line starts with $L this is the line that python interpreter

    reads.

    % -et the permission for the file by using chmod "x file. The file uses the line that is the most important line to

     be used:

    $LGusrGlocalGbinGpython

    % This explains the pathname that is gi!en to the python interpreter and it is independent of the en!ironment

     programs.

    % Absolute pathname should be included so that the interpreter can interpret and execute the code accordingly.

    The sample code that is written:

    $L GbinGsh

    $ rite your code here

    exec python pen() method allows the file to get opened in binary mode to mae it portable for $ use.

    s = f.read(D)

  • 8/18/2019 python interview q & A

    8/20

    x, y, 0 = struct.unpac(;6hhl;, s)

    The I6 is used to show the format string that allows the string to be con!erted in big%endian data form. Eor

    homogenous list of data the array module can be used that will allow the data to be ept more organi0ed

    fashion.

     hat is the process to run sub'process with

    pipes that connect both input and output?

    The popen7() module is used to run the sub%process but due to some difficulty in processing lie creation of

    deadloc that eep a process bloced that wait for the output from the child and child is waiting for the input.

    The dead loc occurs due to the fact that parent and child doesnBt ha!e the synchroni0ation and both are

    waiting to get the processor to pro!ide the resources to one another. Pse of popenQ() method allow the reading

    of stdout and stderr to tae place where the internal buffer increases and there is no read() taes place to share

    the resources. popen7() tae care of the deadloc by pro!iding the methods lie wait() and waitpid() that

    finishes a process first and when a reuest comes it hands o!er the responsibility to the process that is waiting

    for the resources.

    The program is used to show the process and run it.

    import popen7

    fromchild, tochild = popen7.popen7(;command;)

    tochild.write(;inputRn;)

    tochild.flush()

    output = fromchild.readline()

     hat are the different ways to generate random

    numbers?

    Handom module is the standard module that is used to generate the random number.

    The method is defined as:

    import random

    random.random()

    The statement random.random() method return the floating point number that is in the range of &', #). 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 Handom can be done to show the multi%threading

     programs that creates different instance of indi!idual 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). *t returns the elements byselecting it randomly from the range that is specified. *t doesnBt build a range object.

  • 8/18/2019 python interview q & A

    9/20

    % uniform(a, b): it chooses a floating point number that is defined in the range of &a,b).*yt returns the floating

     point number 

    % normal!ariate(mean, sde!): it is used for the normal distribution where the mu is a mean and the sde! is a

    sigma that is used for standard de!iation.

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

     rite a program to show the singleton pattern

    used in python.

    -ingleton patter is used to pro!ide a mechanism that limits the number of instances that can be used by one

    class. *t also allows the same object to be shared between many different parts of the code. This allows the

    global !ariables to be used as the actual data that is used is hidden by the singleton class interface. The

    singleton class interface can ha!e only one public member and one class method andle. Fri!ate constructors

    are not used to create an object that is used outside the class. The process waits for the static member function

    to create new instances and return the singleton object.

    The code that is used to call the singleton object is:

    -ingletonS -ingleton::andle()

    M

      if( Lpsingle )

    M

      psingle = new -ingleton

      O

      return Upsingle

    O

    Python in the eeds(

    While it’s true that the best developers don’t waste time committing to memory

    that which can easily be found in a language specification or AP document!

    there are certain key features and capabilities of any programming language that

    any expert can! and should! be expected to be well"versed in# ere are some

    Fython%specific examples:

    Q: Why use function decorators? Give an example.

    A decorator is essentially a callable Fython object that is used to modify or extend a

    function or class definition. >ne of the beauties of decorators is that a single decorator 

    definition can be applied to multiple functions (or classes). ?uch can thereby be

  • 8/18/2019 python interview q & A

    10/20

    accomplished with decorators that would otherwise reuire lots of boilerplate (or e!en

    worse redundantL) code. Elas , for example, uses decorators as the mechanism for

    adding new endpoints to a web application. xamples of some of the more common

    uses of decorators include adding synchroni0ation, type enforcement, logging, or

     preGpost conditions to a class or function.

    Q: What are lambda expressions, list comprehensions and generator expressions?

    What are the advantages and appropriate uses of each?

     Lambda expressions are a shorthand techniue for creating single line, anonymous

    functions. Their simple, inline nature often V though not always V leads to more

    readable and concise code than the alternati!e of formal function declarations. >n the

    other hand, their terse inline nature, by definition, !ery much limits what they are

    capable of doing and their applicability. 1eing anonymous and inline, the only way to

    use the same lambda function in multiple locations in your code is to specify itredundantly.

     List comprehensions pro!ide a concise syntax for creating lists. Kist comprehensions

    are commonly used to mae lists where each element is the result of some

    operation(s) applied to each member of another seuence or iterable. They can also be

    used to create a subseuence of those elements whose members satisfy a certain

    condition. *n Fython, list comprehensions pro!ide an alternati!e to using the built%

    in map()and filter() functions.

    As the applied usage of lambda expressions and list comprehensions can o!erlap,opinions !ary widely as to when and where to use one !s. the other. >ne point to bear

    in mind, though, is that a list comprehension executes somewhat faster than a

    comparable solution using map and lambda (some uic tests yielded a performance

    difference of roughly #'W). This is because calling a lambda function creates a new

    stac frame while the expression in the list comprehension is e!aluated without doing

    so.

    Generator expressions are syntactically and functionally similar to list

    comprehensions but there are some fairly significant differences between the ways the

    two operate and, accordingly, when each should be used. *n a nutshell, iterating o!er agenerator expression or list comprehension will essentially do the same thing, but the

    list comprehension will create the entire list in memory first while the generator

    expression will create the items on the fly as needed. Jenerator expressions can

    therefore be used for !ery large (and e!en infinite) seuences and their la0y (i.e., on

    demand) generation of !alues results in impro!ed performance and lower memory

    usage. *t is worth noting, though, that the standard Fython list methods can be used on

    the result of a list comprehension, but not directly on that of a generator expression.

    http://flask.pocoo.org/http://flask.pocoo.org/http://flask.pocoo.org/

  • 8/18/2019 python interview q & A

    11/20

    Q: Consider the two approaches below for initialiing an array and the arrays that

    will result. !ow will the resulting arrays differ and why should you use one

    initialiation approach vs. the other?

    >>> # INITIALIZING AN ARRAY -- METHOD

    !!!

    >>> " $$%&%'% * '

    >>> "

    $$% &% '% % $% &% '% % $% &% '%

    >>>

    >>>

    >>> # INITIALIZING AN ARRAY -- METHOD &

    !!!

    >>> + $$%&%'% f,r i. ra./e(')

    >>> +

    $$% &% '% % $% &% '% % $% &% '%

    >>>

    >>> # 0HI1H METHOD 2HO3LD YO3 32E AND 0HY4

    hile both methods appear at first blush to produce the same result, there is an

    extremely significant difference between the two. ?ethod 7 produces, as you would

    expect, an array of Q elements, each of which is itself an independent C%element array.

    *n method #, howe!er, the members of the array all point to the same object. This can

    lead to what is most liely unanticipated and undesired beha!ior as shown below.

    >>> # MODI5YING THE " ARRAY 5ROM THE 6RIOR 1ODE 2NI66ET7

    >>> "$8$' 99

    >>> "

    $$% &% '% 99% $% &% '% 99% $% &% '% 99

    >>> # 3H-OH% DON:T THIN; YO3 0ANTED THAT TO HA66EN<

    !!!

    >>>

  • 8/18/2019 python interview q & A

    12/20

    >>> # MODI5YING THE + ARRAY 5ROM THE 6RIOR 1ODE 2NI66ET7

    >>> +$8$' 99

    >>> +

    $$% &% '% 99% $% &% '% % $% &% '%

    >>> # THAT:2 MORE LI;E 0HAT YO3 E=6E1TED<

    !!!

    Q: What will be printed out by the second append"# statement below?

    >>> def appe.d(lit$)7

    !!! # appe.d t?e le./t? ,f a lit t, t?e lit

    !!! lit!appe.d(le.(lit))

    !!! ret@r. lit

    !!!

    >>> appe.d($a%b)

    $a% b% &

    >>>

    >>> appe.d() # Balli./ Cit? ., ar/ @e defa@lt lit al@e ,f $

    $8

    >>>

    >>> appe.d() # b@t C?at ?appe. C?e. Ce AGAIN Ball appe.d Cit? .,

    ar/4

    hen the default !alue for a function argument is an expression, the expression ise!aluated only once, not e!ery time the function is called. Thus, once the list

    argument has been initiali0ed to an empty array, subseuent calls to append without

    any argument specified will continue to use the same array to which list was

    originally initiali0ed. This will therefore yield the following, presumably unexpected,

     beha!ior:

    >>> appe.d() # firt Ball Cit? ., ar/ @e defa@lt lit al@e ,f $

    $8

    >>> appe.d() # b@t t?e. l,, C?at ?appe.!!!

  • 8/18/2019 python interview q & A

    13/20

    $8%

    >>> appe.d() # @BBeie Ball eep e"te.di./ t?e ame defa@lt

    lit<

    $8% % &

    >>> appe.d() # a.d , ,.% a.d , ,.% a.d , ,.!!!

    $8% % &% '

    Q: !ow might one modify the implementation of the $append% method in the

     previous &uestion to avoid the undesirable behavior described there?

    The following alternati!e implementation of the append method would be one of a

    number of ways to a!oid the undesirable beha!ior described in the answer to the

     pre!ious uestion:

    >>> def appe.d(litN,.e)7

    !!! if lit i N,.e7

      lit $

      # appe.d t?e le./t? ,f a lit t, t?e lit

    !!! lit!appe.d(le.(lit))

    !!! ret@r. lit

    !!!

    >>> appe.d()

    $8

    >>> appe.d()

    $8

    Q: !ow can you swap the values of two variables with a single line of 'ython code?

    +onsider this simple example:

    >>> " =

    >>> + Y

    *n many other languages, swapping the !alues of x and y reuires that you to do the

    following:

  • 8/18/2019 python interview q & A

    14/20

    >>> tmp "

    >>> " +

    >>> + tmp

    >>> "% +

    (Y% =)

    1ut in Fython, maes it possible to do the swap with a single line of code (thans to

    implicit tuple pacing and unpacing) as follows:

    >>> "%+ +%"

    >>> "%+

    (Y% =)

    Q: What will be printed out by the last statement below?

    >>> flit $

    >>> f,r i i. ra./e(')7

    !!! flit!appe.d(lambda7 i)

    !!!

    >>> $f() f,r f i. flit # C?at Cill t?i pri.t ,@t4

    *n any closure in Fython, !ariables are bound by name. Thus, the abo!e line of code

    will print out the following:

    $&% &% &

    Fresumably not what the author of the abo!e code intendedL

    A woraround is to either create a separate function or to pass the args by name e.g.:

    >>> flit $

    >>> f,r i i. ra./e(')7

    !!! flit!appe.d(lambda i i 7 i)

    !!!

    >>> $f() f,r f i. flit

    $8% % &

    http://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmineshttp://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines

  • 8/18/2019 python interview q & A

    15/20

    Q: What are the (ey differences between 'ython ) and *?

    Although Fython 7 is formally considered legacy at this point, its use is still

    widespread enough that is important for a de!eloper to recogni0e the differences

     between Fython 7 and Q.

    ere are some of the ey differences that a de!eloper should be aware of:

    • Text and Data instead of Unicode and 8-bit strings.  Fython Q.' uses the concepts of text and

    (binary) data instead of Pnicode strings and D%bit strings. The biggest ramification of this is

    that any attempt to mix text and data in Fython Q.' raises a Typerror (to combine the two

    safely, you must decode bytes or encode Pnicode, but you need to now the proper 

    encoding, e.g. PTE%D)

    • This addresses a longstanding pitfall for naX!e Fython programmers. *n Fython 7, mixing

    Pnicode and D%bit data would wor if the string happened to contain only 5%bit (A-+**) bytes, but you would get Pnicode/ecoderror if it contained non%A-+** !alues. ?oreo!er,

    the exception would happen at the combination point, not at the point at which the non%

    A-+** characters were put into the str object. This beha!ior was a common source of 

    confusion and consternation for neophyte Fython programmers.

    •  print function. The pri.t statement has been replaced with a pri.t() function

    •  xrange – buh-bye. "ra./e() no longer exists (ra./e() now beha!es lie "ra./e() used

    to beha!e, except it wors with !alues of arbitrary si0e)

    •  AP changes!

    • Fip(), map() and filter() all now return iterators instead of lists

    • diBt!e+(), diBt!item() and diBt!al@e() now return @!iews instead of lists

    • diBt!itere+(), diBt!iteritem() and diBt!iteral@e() are no longer  

    supported

    • "omparison operators. The ordering comparison operators (, , >, >) now raise

    a T+peErr,rexception when the operands donBt ha!e a meaningful natural ordering. -ome

    examples of the ramifications of this include:

    • xpressions lie , 8 > N,.e or le. le. are no longer !alid

    • N,.e N,.e now raises a T+peErr,r instead of returning 5ale

    • -orting a heterogeneous list no longer maes sense V all the elements must be comparable to

    each other 

    ?ore details on the differences between Fython 7 and Q are a!ailable here.

    Q: +s 'ython interpreted or compiled?

    As noted in hy Are There -o ?any FythonsY, this is, franly, a bit of a tric

    uestion in that it is malformed. Fython itself is nothing more than an interfacedefinition (as is true with any language specification) of which there are multiple

    https://docs.python.org/3/whatsnew/3.0.htmlhttps://www.toptal.com/python/why-are-there-so-many-pythonshttps://www.toptal.com/python/why-are-there-so-many-pythonshttps://docs.python.org/3/whatsnew/3.0.htmlhttps://www.toptal.com/python/why-are-there-so-many-pythons

  • 8/18/2019 python interview q & A

    16/20

    implementations. Accordingly, the uestion of whether @Fython is interpreted or

    compiled does not apply to the Fython language itself rather, it applies to each

    specific implementation of the Fython specification.

    Eurther complicating the answer to this uestion is the fact that, in the case of+Fython (the most common Fython implementation), the answer really is @sort of

     both. -pecifically, with +Fython, code is first compiled and then interpreted. ?ore

     precisely, it is not precompiled to nati!e machine code, but rather to bytecode. hile

    machine code is certainly faster, bytecode is more portable and secure. The bytecode

    is then interpreted in the case of +Fython (or both interpreted and compiled to

    optimi0ed machine code at runtime in the case of FyFy).

    Q: What are some alternative implementations to C'ython? When and why might

     you use them?

    >ne of the more prominent alternati!e implementations is Zython, a Fython

    implementation written in Za!a that utili0es the Za!a 9irtual ?achine (Z9?). hile

    +Fython produces bytecode to run on the +Fython 9?, Zython produces Za!a

     bytecode to run on the Z9?.

    Another is *ronFython, written in +$ and targeting the .[T stac. *ronFython runs

    on ?icrosoftBs +ommon Kanguage Huntime (+KH).

    As also pointed out in hy Are There -o ?any FythonsY, it is entirely possible to

    sur!i!e without e!er touching a non%+Fython implementation of Fython, but there are

    ad!antages to be had from switching, most of which are dependent on your

    technology stac.

    Another noteworthy alternati!e implementation is FyFy whose ey features include:

    • #peed. Thans to its Zust%in%Time (Z*T) compiler, Fython programs often run faster on FyFy.

    •  $emory usage. Karge, memory%hungry Fython programs might end up taing less space with

    FyFy than they do in +Fython.

    • "ompatibi%ity. FyFy is highly compatible with existing python code. *t supports cffi and can

    run popular Fython libraries lie Twisted and /jango.

    • #andboxing. FyFy pro!ides the ability to run untrusted code in a fully secure way.

    • #tac&%ess mode. FyFy comes by default with support for stacless mode, pro!iding micro%

    threads for massi!e concurrency.

    Q: What%s your approach to unit testing in 'ython?

    The most fundamental answer to this uestion centers around FythonBs unittest testing

    framewor. 1asically, if a candidate doesnBt mention unittest when answering this

    uestion, that should be a huge red flag.

    http://pypy.org/http://www.jython.org/http://www.jython.org/http://ironpython.net/http://ironpython.net/https://www.toptal.com/python/why-are-there-so-many-pythonshttp://pypy.org/http://pypy.org/https://pypi.python.org/pypi/cffi/0.8.2https://pypi.python.org/pypi/cffi/0.8.2https://twistedmatrix.com/trac/https://www.djangoproject.com/https://www.djangoproject.com/https://docs.python.org/2/library/unittest.htmlhttps://docs.python.org/2/library/unittest.htmlhttp://pypy.org/http://www.jython.org/http://ironpython.net/https://www.toptal.com/python/why-are-there-so-many-pythonshttp://pypy.org/https://pypi.python.org/pypi/cffi/0.8.2https://twistedmatrix.com/trac/https://www.djangoproject.com/https://docs.python.org/2/library/unittest.html

  • 8/18/2019 python interview q & A

    17/20

    unittest supports test automation, sharing of setup and shutdown code for tests,

    aggregation of tests into collections, and independence of the tests from the reporting

    framewor. The unittest module pro!ides classes that mae it easy to support these

    ualities for a set of tests.

    Assuming that the candidate does mention unittest (if they donBt, you may just want to

    end the inter!iew right then and thereL), you should also as them to describe the ey

    elements of the unittest framewor namely, test fixtures, test cases, test suites and test

    runners.

    A more recent addition to the unittest framewor is moc . moc allows you to replace

     parts of your system under test with moc objects and mae assertions about how they

    are to be used. moc is now part of the Fython standard library, a!ailable as

    unittest.moc in Fython Q.Q onwards.

    The !alue and power of moc are well explained in An *ntroduction to ?ocing in

    Fython. As noted therein, system calls are prime candidates for mocing: whether

    writing a script to eject a +/ dri!e, a web ser!er which remo!es antiuated cache

    files from Gtmp, or a socet ser!er which binds to a T+F port, these calls all feature

    undesired side%effects in the context of unit tests. -imilarly, eeping your unit%tests

    efficient and performant means eeping as much @slow code as possible out of the

    automated test runs, namely filesystem and networ access.

    $%ote: This question is for Python developers who are also experienced in &ava#'

    Q: What are some (ey differences to bear in mind when coding in 'ython vs. ava?

     Disc%aimer '(. The differences between Za!a and Fython are numerous and would

    liely be a topic worthy of its own (lengthy) post. 1elow is just a brief sampling of

    some ey differences between the two languages.

     Disc%aimer '). The intent here is not to launch into a religious battle o!er the merits

    of Fython !s. Za!a (as much fun as that might beL). Hather, the uestion is really just

    geared at seeing how well the de!eloper understands some practical differences

     between the two languages. The list below therefore deliberately a!oids discussing the

    arguable ad!antages of Fython o!er Za!a from a programming producti!ity

     perspecti!e.

    ith the abo!e two disclaimers in mind, here is a sampling of some ey differences to

     bear in mind when coding in Fython !s. Za!a:

    •  Dynamic *s static typing. >ne of the biggest differences between the two languages is that

    Za!a is restricted to static typing whereas Fython supports dynamic typing of !ariables.

    • #tatic *s. c%ass methods. A static method in Za!a does not translate to a Fython class method.

    • *n Fython, calling a class method in!ol!es an additional memory allocation that calling a

    static method or function does not.

    https://pypi.python.org/pypi/mockhttps://www.toptal.com/python/an-introduction-to-mocking-in-pythonhttps://www.toptal.com/python/an-introduction-to-mocking-in-pythonhttps://pypi.python.org/pypi/mockhttps://www.toptal.com/python/an-introduction-to-mocking-in-pythonhttps://www.toptal.com/python/an-introduction-to-mocking-in-python

  • 8/18/2019 python interview q & A

    18/20

    • *n Za!a, dotted names (e.g., foo.bar.method) are looed up by the compiler, so at runtime it

    really doesnBt matter how many of them you ha!e. *n Fython, howe!er, the looups occur at

    runtime, so @each dot counts.

    •  $ethod o*er%oading. hereas Za!a reuires explicit specification of multiple same%named

    functions with different signatures, the same can be accomplished in Fython with a singlefunction that includes optional arguments with default !alues if not specified by the caller.

    • #ing%e *s. doub%e +uotes. hereas the use of single uotes !s. double uotes has significance

    in Za!a, they can be used interchangeably in Fython (but no, it wonBt allow beginnning

    the same string with a double uote and trying to end it with a single uote, or !ice !ersaL).

    • Getters and setters ,not. Jetters and setters in Fython are superfluous rather, you should

    use the IpropertyB built%in (thatBs what itBs forL). *n Fython, getters and setters are a waste of 

     both +FP and programmer time.

    • "%asses are optiona%. hereas Za!a reuires e!ery function to be defined in the context of anenclosing class definition, Fython has no such reuirement.

    •  ndentation matters/ in Fython. This bites many a newbie Fython programmer.

    )he *ig Picture

    An expert knowledge of Python extends well beyond the technical minutia of the

    language# A Fython expert will ha!e an in%depth understanding and appreciation of

    FythonBs benefits as well as its limitations. Accordingly, here are some sample

    uestions that can help assess this dimension of a candidateBs expertise:

    Q: What is 'ython particularly good for? When is using 'ython the -right choice

     for a pro/ect?

    Although lies and dislies are highly personal, a de!eloper who is @worth his or her

    salt will highlight features of the Fython language that are generally considered

    ad!antageous (which also helps answer the uestion of what Fython is @particularly

    good for). -ome of the more common !alid answers to this uestion include:

    •  0ase of use and ease of refactoring1 thans to the flexibility of FythonBs syntax, which maes

    it especially useful for rapid prototyping.

    •  $ore compact code1 thans again to FythonBs syntax, along with a wealth of functionally%

    rich Fython libraries (distributed freely with most Fython language implementations).

    •  A dynamica%%y-typed and strong%y-typed %anguage1 offering the rare combination of code

    flexibility while at the same time a!oiding pesy implicit%type%con!ersion bugs.

    •  t2s free and open source [eed we say moreY

    ith regard to the uestion of when using Fython is the @right choice for a project,

    the complete answer also depends on a number of issues orthogonal to the language

  • 8/18/2019 python interview q & A

    19/20

    itself, such as prior technology in!estment, sill set of the team, and so on. Although

    the uestion as stated abo!e implies interest in a strictly technical answer, a de!eloper

    who will raise these additional issues in an inter!iew will always @score more points

    with me since it indicates an awareness of, and sensiti!ity to, the @bigger picture

    (i.e., beyond just the technology being employed). +on!ersely, a response that Fythonis always the right choice is a clear sign of an unsophisticated de!eloper.

    Q: What are some drawbac(s of the 'ython language?

    Eor starters, if you now a language well, you now its drawbacs, so responses such

    as @thereBs nothing * donBt lie about it or @it has no drawbacs are !ery telling

    indeed.

    The two most common !alid answers to this uestion (by no means intended as an

    exhausti!e list) are:

    • The G%oba% nterpreter Loc& ,GL. +Fython (the most common Fython implementation) is

    not fully thread safe. *n order to support multi%threaded Fython programs, +Fython pro!ides

    a global loc that must be held by the current thread before it can safely access Fython

    objects. As a result, no matter how many threads or processors are present, only one thread is

    e!er being executed at any gi!en time. *n comparison, it is worth noting that the FyFy

    implementation discussed earlier in this article pro!ides a stacless mode that supports

    micro%threads for massi!e concurrency.

    •  0xecution speed. Fython can be slower than compiled languages since it is interpreted. (ell,

    sort of. -ee our  earlier discussion on this topic.)

    What are the rules for local and global

    variables in Python?

    *f a !ariable is defined outside function then it is implicitly global. *f !ariable is assigned new

    !alue inside the function means it is local. *f we want to mae it global we need to explicitly

    define it as global. 9ariable referenced inside the function are implicit global. Eollowing code

    snippet will explain further the difference

    $LGusrGbinGpython

    $ Eilename: !ariable3localglobal.py

    def fun#(a):

      print a:, a

      a= QQ

      print local a: , a

    a = #''

    fun#(a)

    https://wiki.python.org/moin/GlobalInterpreterLockhttps://www.toptal.com/python#aboutPyPyhttps://www.toptal.com/python#interpretedOrCompiledhttps://www.toptal.com/python#interpretedOrCompiledhttps://www.toptal.com/python#interpretedOrCompiledhttps://wiki.python.org/moin/GlobalInterpreterLockhttps://www.toptal.com/python#aboutPyPyhttps://www.toptal.com/python#interpretedOrCompiled

  • 8/18/2019 python interview q & A

    20/20

     print a outside fun#:, a

    def fun7():

      global b

      print b: , b

      b = QQ

      print global b:, b

     b =#''

    fun7()

     print b outside fun7, b

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    >utput

    < python !ariable3localglobal.pya: #''

    local a: QQ

    a outside fun#: #''

     b :#''

    global b: QQ

     b outside fun7: QQ