Which THREE of the following represent common issues when using __slots__?
Otherwise, the child gets a dictionary.
Why this answer
Slots can break pickling in some cases, make multiple inheritance tricky, and prevent adding attributes dynamically.
209 questions total · 3pages · All types, answers revealed
Page 3 of 3
Which THREE of the following represent common issues when using __slots__?
Otherwise, the child gets a dictionary.
Why this answer
Slots can break pickling in some cases, make multiple inheritance tricky, and prevent adding attributes dynamically.
In a Tkinter grid layout, you want a button to span across two columns. Which parameter should you use?
columnspan is the correct parameter for merging grid columns.
Why this answer
The columnspan parameter in the grid() method manager allows a widget to occupy multiple columns.
You are building a Tkinter application and need to ensure that a Label widget expands to fill any extra horizontal space when the parent window is resized. Which configuration for the grid() layout manager achieves this?
Setting the column weight allows expansion, and sticky='ew' forces the widget to fill that space.
Why this answer
The sticky parameter with 'ew' (east and west) ensures the widget stretches horizontally, while columnconfigure with weight > 0 allows the column to expand.
You are implementing the Observer pattern. Why should you avoid using a strong reference to the observers in the subject's list?
Weak references allow the garbage collector to reclaim the observer even if it's in the subject's list.
Why this answer
Strong references prevent garbage collection of the observers, leading to memory leaks if observers are meant to be temporary.
What is the primary difference between @classmethod and @staticmethod?
This is the fundamental distinction.
Why this answer
@classmethod receives the class as the first argument, while @staticmethod receives no implicit class or instance argument.
What is the correct way to specify the title of a Tkinter window?
title() sets the window header text.
Why this answer
The title() method is called on the root window object.
Which method on a widget instance causes it to be removed from the display, but not destroyed?
pack_forget() removes the widget from the display.
Why this answer
The pack_forget() (or grid_forget()) method hides a widget from the layout manager.
Which THREE of the following are valid ways to configure a widget's appearance after it has been created?
Dictionary-style access is supported for configuration.
Why this answer
Widget appearance can be configured via the config() method, using dictionary-style access, or by directly calling attribute-specific methods if they exist (though config is standard).
When using configparser, how do you handle multiline values?
Indentation is the standard way to signify continuation of a value.
Why this answer
You indent lines following the initial line within the option.
When using sqlite3.Row, what is the primary benefit over using a standard tuple?
This feature makes code more readable and robust against schema changes.
Why this answer
sqlite3.Row allows accessing column values by name (string keys) instead of just numerical indices.
Which magic method enables index access (e.g., obj[i])?
This is for retrieval.
Why this answer
The __getitem__ method allows an object to support indexing.
Which comment style is preferred for block comments in Python?
This is the PEP 8 standard for block comments.
Why this answer
Block comments should consist of paragraphs of text, each starting with a # and a single space.
Which TWO of the following are true about magic methods?
They are the standard hooks for operators like +, -, etc.
Why this answer
Magic methods start and end with double underscores, and they allow objects to integrate with Python's built-in syntax.
You are using 'concurrent.futures.ThreadPoolExecutor' to fetch data from multiple REST APIs. What happens if an exception is raised inside a thread?
The Future object encapsulates the result or the exception.
Why this answer
Exceptions raised in a future are captured and re-raised when calling result() on the Future object returned by submit().
Which TWO of the following statements correctly describe the behavior of the Tkinter 'pack' geometry manager?
These are the valid values for the 'side' parameter.
Why this answer
Pack stacks widgets based on the 'side' argument and 'fill' determines how they occupy available space.
You want to trigger a function when a user releases a key. Which event string should you use with bind()?
<KeyRelease> is the correct event string.
Why this answer
The '<KeyRelease>' event is used to detect when a key is released.
Which THREE of the following are valid ways to pass arguments to a function called by a Tkinter button command?
Using default arguments in a lambda is a robust way to capture values.
Why this answer
Using lambda or functools.partial are the standard ways to handle arguments in button commands.
You are configuring a logging FileHandler. What does the 'mode' parameter control?
The mode parameter specifies how the file is opened (e.g., 'a', 'w').
Why this answer
The 'mode' parameter controls the file opening mode (e.g., 'a' for append, 'w' for write).
You are using the pack() geometry manager and want to place a frame at the bottom of the window, ensuring it stays there even when other widgets are added. Which configuration is correct?
This anchors the frame to the bottom and makes it expand horizontally.
Why this answer
The 'side' parameter set to 'bottom' and 'fill' set to 'x' is the standard way to anchor a widget to the bottom edge.
You want to retrieve a list of all section names from a ConfigParser object. How do you do this?
This returns a list of section names.
Why this answer
The sections() method returns a list containing all section names except the DEFAULT section.
Which TWO of the following statements about the Python 'requests' library are correct?
Requests is built on top of the powerful urllib3 library.
Why this answer
The library handles connection pooling automatically when using Sessions, and it is built on top of 'urllib3'.
Which TWO of the following are valid ways to create a singleton in Python?
Can be used, though metaclasses are cleaner.
Why this answer
Modules are natural singletons, and metaclasses can be used to control instance creation.
Which widget is most suitable for displaying multi-line, editable text?
Text is for multi-line text.
Why this answer
The Text widget provides a flexible, multi-line text area.
Which TWO of the following are valid conventions for naming in Python according to PEP 8?
Correct convention for classes.
Why this answer
Functions should use snake_case, and classes should use PascalCase.
You are building a REST client that needs to handle 429 Too Many Requests status codes. Which strategy is most effective when implementing an automatic retry mechanism?
Exponential backoff with jitter is the industry standard for handling rate limits.
Why this answer
Implementing exponential backoff ensures that you do not overwhelm the server while waiting for the rate limit to reset.
Which THREE practices improve documentation maintenance?
Keeps info accurate.
Why this answer
Using standard formats, using tools, and regular updates are key.
Which attribute of a Button widget controls the text displayed on it?
text is the attribute for the button label.
Why this answer
The 'text' parameter defines the display label of the button.
What happens when you add two objects of a class that implements __add__?
This is how operator overloading works.
Why this answer
The __add__ method is automatically called by the interpreter when the '+' operator is used.
Which TWO of the following are required to successfully write a row to a CSV file?
The writer object handles the formatting.
Why this answer
You need an open file object and a csv.writer instance.
Which THREE of the following are valid Tkinter variable classes used for tracking widget states?
Used for integer values.
Why this answer
StringVar, IntVar, DoubleVar, and BooleanVar are the standard Tkinter variable classes.
Which practice is recommended when dealing with 'bare' except clauses in Python?
This prevents catching unintended system-level exceptions.
Why this answer
Bare 'except:' clauses catch SystemExit and KeyboardInterrupt, which can prevent the user from stopping a program.
When using the 'requests' library to perform a GET request, which parameter should be passed to the 'params' argument to include query string parameters in the URL?
A dictionary represents the query parameters correctly.
Why this answer
The 'params' argument expects a dictionary of key-value pairs which the library automatically encodes and appends to the URL.
You are using configparser.ConfigParser to read a configuration file. You have a file where option names are case-sensitive. How do you ensure the parser respects this casing?
Setting optionxform to a function that returns the input string prevents lowercase conversion.
Why this answer
By default, ConfigParser converts keys to lowercase. You must override the optionxform method of the parser instance.
If you define a class with a metaclass that has a custom __call__ method, when is that __call__ method executed?
Metaclass __call__ intercepts the instantiation of its class objects.
Why this answer
The metaclass's __call__ method is invoked whenever the class created by that metaclass is instantiated (i.e., when you call the class name like MyClass()).
You are configuring logging using a dictConfig. You want to send logs to a RotatingFileHandler. Which key must you define in the 'handlers' section?
The 'class' key identifies the handler implementation.
Why this answer
The 'class' key is required to specify the handler type, e.g., 'logging.handlers.RotatingFileHandler'.
You need a color chooser dialog in your application. Which module contains this functionality?
This module contains the color selection dialog.
Why this answer
The 'tkinter.colorchooser' module provides the askcolor() function.
You need to configure the logging module to capture logs from multiple modules while ensuring that logs from third-party libraries (e.g., 'urllib3') are only captured at the WARNING level. How do you set this?
This explicitly sets the log level for the specified library logger.
Why this answer
You can configure individual loggers using getLogger() and setting their specific level attribute.
Which TWO of the following are valid ways to terminate a Tkinter script gracefully?
Correctly exits the event loop.
Why this answer
Calling destroy() on the root window or calling the quit() method are standard ways to end a GUI session.
Which method is used to customize the behavior of the 'in' operator?
This is the correct magic method.
Why this answer
The __contains__ method is called when using the 'in' or 'not in' operators.
Which TWO of the following are secure coding practices in Python?
Pickle is inherently insecure.
Why this answer
Avoiding dangerous functions and validating all inputs are key security practices.
This is the idiomatic way to handle optional keys in dictionaries.
Why this answer
The dict.get() method provides a way to access a key with a default value if the key does not exist, preventing a KeyError.
What is the primary function of the 'bg' parameter in a widget configuration?
bg stands for background.
Why this answer
The 'bg' (or background) parameter sets the background color of the widget.
Which THREE of the following are valid logging levels?
Valid level.
Why this answer
DEBUG, INFO, and WARNING are valid levels.
To prevent a user from editing text in a widget, which configuration option should you set?
state=tk.DISABLED effectively makes the widget uneditable.
Why this answer
Setting 'state' to 'disabled' prevents user interaction with the widget.
Which magic method should you implement to make your objects support the 'with' statement context manager?
These are the mandatory methods for the context manager protocol.
Why this answer
The __enter__ and __exit__ methods are required to implement the context manager protocol.
Which function is used to check if an object is an instance of a class?
This handles inheritance correctly.
Why this answer
isinstance(obj, Class) is the standard way to check inheritance.
You want to bind a function 'on_click' to a left mouse button click on a Button widget. Which event sequence string is correct?
<Button-1> represents the left mouse click.
Why this answer
The event sequence '<Button-1>' corresponds to the primary (left) mouse button.
In the context of the Factory pattern in Python, what is a typical benefit of using a registry-based approach instead of a large if-else block?
This is the open/closed principle in action.
Why this answer
Registry-based factories allow for decoupled code where new classes can be registered without modifying the factory's core logic.
How do you properly handle a non-200 status code when using 'requests' if you want to avoid manual status code checking?
This is the built-in method to handle error status codes.
Why this answer
Calling response.raise_for_status() will raise an HTTPError exception if the status code indicates an error (4xx or 5xx).
You are processing a CSV file using csv.DictReader. If your input file lacks a header row, how do you provide the field names?
This correctly maps columns to the provided field names.
Why this answer
You pass the 'fieldnames' argument to the constructor to define the headers explicitly.
You are debugging a legacy application and need to ensure that resources like file handles are always closed. Which construct is preferred?
This is the Pythonic way to handle resource management.
Why this answer
The 'with' statement (context manager) ensures that cleanup code is executed even if an exception occurs.
Consider a class that uses a metaclass to automatically register subclasses in a dictionary. If you want to prevent the base class itself from being registered, how should the metaclass be implemented?
The __init__ method is invoked after the class creation, allowing you to filter out the base class based on attributes or names.
Why this answer
The metaclass __init__ method receives the class object. By checking the class name or using a specific attribute (e.g., _is_base), you can conditionally skip registration.
How do you set a specific font for a widget?
The font parameter is the standard way to set typography.
Why this answer
The 'font' parameter accepts a tuple or string defining font family, size, and style.
You are using sqlite3 and need to enforce foreign key constraints. How do you enable them?
This is the correct SQLite pragma command.
Why this answer
You must execute the command 'PRAGMA foreign_keys = ON;' on the connection.
Why might you use the __init_subclass__ hook instead of a metaclass?
Metaclass conflicts arise when multiple classes have different metaclasses; __init_subclass__ avoids this.
Why this answer
__init_subclass__ provides a simpler way to perform logic when a subclass is created, without the complexity and inheritance issues associated with custom metaclasses.
You are building a custom HTTP client and need to handle persistent connections (keep-alive). What is the primary role of the 'Connection' header?
This is the purpose of the Connection header.
Why this answer
The 'Connection: keep-alive' header tells the server that the client wants to reuse the same TCP connection for multiple requests.
Which TWO of the following are true about the sqlite3.Cursor object?
Cursors can iterate over result sets.
Why this answer
The cursor is used to execute SQL and retrieve results.
Which THREE of the following are valid ways to pass data to a REST API using 'requests'?
Used for sending JSON serialized data.
Why this answer
The 'params', 'data', and 'json' arguments allow different ways of sending information in requests.
You have a Tkinter Entry widget and want to retrieve the text currently entered by the user. Which method do you call on the Entry instance?
get() is the correct method to extract the string content from an Entry widget.
Why this answer
The get() method is used to retrieve the current contents of Entry and Text widgets.
Page 3 of 3
Practice PCPP1 by domain
Target a specific domain to shore up weak areas.