The Conditional Variable Assignment Operator in a Makefile

Last updated: March 18, 2024

make conditional assignment

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

1. Overview

Make is a de-facto tool for building and running software projects. In this article, we’ll learn about the conditional variable assignment operator ( ?= ) using a simple use case .

Let’s start by writing a simple Makefile and adding a target called greet :

Now, let’s use the make command to execute the greet target:

We should note that we used the @ prefix before the target definition. That instructs the Make tool to suppress the command definition while showing the output and limiting the output to the result of the executed command.

Great! We’ve got a basic setup ready with us. We’ll extend this Makefile in the next section by using variable definitions.

3. Variables in a Makefile

So far, the greeting shown to the user by our Makefile is a static text, so all users get the same greeting message. To make it dynamic, let’s include the login username in the message so that the greeting is more personalized for each user.

Let’s define a user variable and initialize it with the output of the whoami command by using the assignment ( = ) operator:

We should note that we followed a standard naming convention of using lowercase letters in the variable name because the variable’s scope is limited to the Makefile .

Further, let’s now use this variable in the greet target by referencing this variable using the $() operator :

Next, let’s see the revised greeting in action by executing the greet target again:

It looks like we’ve got it right!

4. Using the Conditional Variable Assignment Operator ( ?= )

Now that we understand the basics of using a variable in a Makefile , we’ll be more comfortable understanding the ?= operator, which is used for conditional variable assignment in a Makefile .

To that end, let’s extend our Makefile by allowing the user to specify the username to be mentioned in the greeting  instead of using the login name. However, we want to keep this optional, so if the user doesn’t specify the value, we still resort to the default behavior of using the login name.

As part of the refactoring exercise, we need to use the ?= operator in place of the = operator so that we don’t override the value if the variable already holds a value. Secondly, we’ll now use uppercase letters in the variable name because we’re extending its scope by letting the user define it from the outside:

Next, let’s see the two scenarios in action:

In the first scenario, we must note that we passed the USER variable’s value as an argument to the make command to get a custom username. On the other hand, in the second scenario, we didn’t pass the value of the USER variable, so we got the default login name in the greeting message.

Fairly straightforward, right? That’s all we need to know for using the conditional operator to create an effective Makefile for our projects.

5. Conclusion

In this tutorial, we took a step-by-step approach to learn about the conditional variable assignment in a Makefile . We first understood the basics of using variables in a Makefile , followed by using the ?= operator for a more advanced use case.

Managing Projects with GNU Make, 3rd Edition by Robert Mecklenburg

Get full access to Managing Projects with GNU Make, 3rd Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 3. Variables and Macros

We’ve been looking at makefile variables for a while now and we’ve seen many examples of how they’re used in both the built-in and user-defined rules. But the examples we’ve seen have only scratched the surface. Variables and macros get much more complicated and give GNU make much of its incredible power.

Before we go any further, it is important to understand that make is sort of two languages in one. The first language describes dependency graphs consisting of targets and prerequisites. (This language was covered in Chapter 2 .) The second language is a macro language for performing textual substitution. Other macro languages you may be familiar with are the C preprocessor, m4 , TEX, and macro assemblers. Like these other macro languages, make allows you to define a shorthand term for a longer sequence of characters and use the shorthand in your program. The macro processor will recognize your shorthand terms and replace them with their expanded form. Although it is easy to think of makefile variables as traditional programming language variables, there is a distinction between a macro “variable” and a “traditional” variable. A macro variable is expanded “in place” to yield a text string that may then be expanded further. This distinction will become more clear as we proceed.

A variable name can contain almost any characters including most punctuation. Even spaces are allowed, but if you value your sanity you should avoid them. The only characters actually disallowed in a variable name are :, #, and =.

Variables are case-sensitive, so cc and CC refer to different variables. To get the value of a variable, enclose the variable name in $( ) . As a special case, single-letter variable names can omit the parentheses and simply use $ letter . This is why the automatic variables can be written without the parentheses. As a general rule you should use the parenthetical form and avoid single letter variable names.

Variables can also be expanded using curly braces as in ${CC} and you will often see this form, particularly in older makefile s. There is seldom an advantage to using one over the other, so just pick one and stick with it. Some people use curly braces for variable reference and parentheses for function call, similar to the way the shell uses them. Most modern makefile s use parentheses and that’s what we’ll use throughout this book.

Variables representing constants a user might want to customize on the command line or in the environment are written in all uppercase, by convention. Words are separated by underscores. Variables that appear only in the makefile are all lowercase with words separated by underscores. Finally, in this book, user-defined functions in variables and macros use lowercase words separated by dashes. Other naming conventions will be explained where they occur. (The following example uses features we haven’t discussed yet. I’m using them to illustrate the variable naming conventions, don’t be too concerned about the righthand side for now.)

The value of a variable consists of all the words to the right of the assignment symbol with leading space trimmed. Trailing spaces are not trimmed. This can occasionally cause trouble, for instance, if the trailing whitespace is included in the variable and subsequently used in a command script:

The variable assignment contains a trailing space that is made more apparent by the comment (but a trailing space can also be present without a trailing comment). When this makefile is run, we get:

Oops, the grep search string also included the trailing space and failed to find the file in ls ’s output. We’ll discuss whitespace issues in more detail later. For now, let’s look more closely at variables.

What Variables Are Used For

In general it is a good idea to use variables to represent external programs. This allows users of the makefile to more easily adapt the makefile to their specific environment. For instance, there are often several versions of awk on a system: awk , nawk , gawk . By creating a variable, AWK , to hold the name of the awk program you make it easier for other users of your makefile . Also, if security is an issue in your environment, a good practice is to access external programs with absolute paths to avoid problems with user’s paths. Absolute paths also reduce the likelihood of issues if trojan horse versions of system programs have been installed somewhere in a user’s path. Of course, absolute paths also make makefile s less portable to other systems. Your own requirements should guide your choice.

Though your first use of variables should be to hold simple constants, they can also store user-defined command sequences such as: [ 4 ]

for reporting on free disk space. Variables are used for both these purposes and more, as we will see.

Variable Types

There are two types of variables in make : simply expanded variables and recursively expanded variables. A simply expanded variable (or a simple variable) is defined using the := assignment operator:

It is called “simply expanded” because its righthand side is expanded immediately upon reading the line from the makefile . Any make variable references in the right-hand side are expanded and the resulting text saved as the value of the variable. This behavior is identical to most programming and scripting languages. For instance, the normal expansion of this variable would yield:

However, if CC above had not yet been set, then the value of the above assignment would be:

$(CC) is expanded to its value (which contains no characters), and collapses to nothing. It is not an error for a variable to have no definition. In fact, this is extremely useful. Most of the implicit commands include undefined variables that serve as place holders for user customizations. If the user does not customize a variable it collapses to nothing. Now notice the leading space. The righthand side is first parsed by make to yield the string $(CC) -M . When the variable reference is collapsed to nothing, make does not rescan the value and trim blanks. The blanks are left intact.

The second type of variable is called a recursively expanded variable. A recursively expanded variable (or a recursive variable) is defined using the = assignment operator:

It is called “recursively expanded” because its righthand side is simply slurped up by make and stored as the value of the variable without evaluating or expanding it in any way. Instead, the expansion is performed when the variable is used . A better term for this variable might be lazily expanded variable, since the evaluation is deferred until it is actually used. One surprising effect of this style of expansion is that assignments can be performed “out of order”:

Here the value of MAKE_DEPEND within a command script is gcc -M even though CC was undefined when MAKE_DEPEND was assigned.

In fact, recursive variables aren’t really just a lazy assignment (at least not a normal lazy assignment). Each time the recursive variable is used, its righthand side is reevaluated. For variables that are defined in terms of simple constants such as MAKE_ DEPEND above, this distinction is pointless since all the variables on the righthand side are also simple constants. But imagine if a variable in the righthand side represented the execution of a program, say date . Each time the recursive variable was expanded the date program would be executed and each variable expansion would have a different value (assuming they were executed at least one second apart). At times this is very useful. At other times it is very annoying!

Other Types of Assignment

From previous examples we’ve seen two types of assignment: = for creating recursive variables and := for creating simple variables. There are two other assignment operators provided by make .

The ?= operator is called the conditional variable assignment operator . That’s quite a mouth-full so we’ll just call it conditional assignment. This operator will perform the requested variable assignment only if the variable does not yet have a value.

Here we set the output directory variable, OUTPUT_DIR , only if it hasn’t been set earlier. This feature interacts nicely with environment variables. We’ll discuss this in the section Where Variables Come From later in this chapter.

The other assignment operator, += , is usually referred to as append . As its name suggests, this operator appends text to a variable. This may seem unremarkable, but it is an important feature when recursive variables are used. Specifically, values on the righthand side of the assignment are appended to the variable without changing the original values in the variable . “Big deal, isn’t that what append always does?” I hear you say. Yes, but hold on, this is a little tricky.

Appending to a simple variable is pretty obvious. The += operator might be implemented like this:

Since the value in the simple variable has already undergone expansion, make can expand $(simple) , append the text, and finish the assignment. But recursive variables pose a problem. An implementation like the following isn’t allowed.

This is an error because there’s no good way for make to handle it. If make stores the current definition of recursive plus new stuff , make can’t expand it again at runtime. Furthermore, attempting to expand a recursive variable containing a reference to itself yields an infinite loop.

So, += was implemented specifically to allow adding text to a recursive variable and does the Right Thing™. This operator is particularly useful for collecting values into a variable incrementally.

Variables are fine for storing values as a single line of text, but what if we have a multiline value such as a command script we would like to execute in several places? For instance, the following sequence of commands might be used to create a Java archive (or jar ) from Java class files:

At the beginning of long sequences such as this, I like to print a brief message. It can make reading make ’s output much easier. After the message, we collect our class files into a clean temporary directory. So we delete the temporary jar directory in case an old one is left lying about, [ 5 ] then we create a fresh temporary directory. Next we copy our prerequisite files (and all their subdirectories) into the temporary directory. Then we switch to our temporary directory and create the jar with the target filename. We add the manifest file to the jar and finally clean up. Clearly, we do not want to duplicate this sequence of commands in our makefile since that would be a maintenance problem in the future. We might consider packing all these commands into a recursive variable, but that is ugly to maintain and difficult to read when make echoes the command line (the whole sequence is echoed as one enormous line of text).

Instead, we can use a GNU make “canned sequence” as created by the define directive. The term “canned sequence” is a bit awkward, so we’ll call this a macro . A macro is just another way of defining a variable in make , and one that can contain embedded newlines! The GNU make manual seems to use the words variable and macro interchangeably. In this book, we’ll use the word macro specifically to mean variables defined using the define directive and variable only when assignment is used.

The define directive is followed by the macro name and a newline. The body of the macro includes all the text up to the endef keyword, which must appear on a line by itself. A macro created with define is expanded pretty much like any other variable, except that when it is used in the context of a command script, each line of the macro has a tab prepended to the line. An example use is:

Notice we’ve added an @ character in front of our echo command. Command lines prefixed with an @ character are not echoed by make when the command is executed. When we run make , therefore, it doesn’t print the echo command, just the output of that command. If the @ prefix is used within a macro, the prefix character applies to the individual lines on which it is used. However, if the prefix character is used on the macro reference, the entire macro body is hidden:

This displays only:

The use of @ is covered in more detail in the section Command Modifiers in Chapter 5 .

When Variables Are Expanded

In the previous sections, we began to get a taste of some of the subtleties of variable expansion. Results depend a lot on what was previously defined, and where. You could easily get results you don’t want, even if make fails to find any error. So what are the rules for expanding variables? How does this really work?

When make runs, it performs its job in two phases. In the first phase, make reads the makefile and any included makefile s. At this time, variables and rules are loaded into make ’s internal database and the dependency graph is created. In the second phase, make analyzes the dependency graph and determines the targets that need to be updated, then executes command scripts to perform the required updates.

When a recursive variable or define directive is processed by make , the lines in the variable or body of the macro are stored, including the newlines without being expanded. The very last newline of a macro definition is not stored as part of the macro. Otherwise, when the macro was expanded an extra newline would be read by make .

When a macro is expanded, the expanded text is then immediately scanned for further macro or variable references and those are expanded and so on, recursively. If the macro is expanded in the context of an action, each line of the macro is inserted with a leading tab character.

To summarize, here are the rules for when elements of a makefile are expanded:

For variable assignments, the lefthand side of the assignment is always expanded immediately when make reads the line during its first phase.

The righthand side of = and ?= are deferred until they are used in the second phase.

The righthand side of := is expanded immediately.

The righthand side of += is expanded immediately if the lefthand side was originally defined as a simple variable. Otherwise, its evaluation is deferred.

For macro definitions (those using define ), the macro variable name is immediately expanded and the body of the macro is deferred until used.

For rules, the targets and prerequisites are always immediately expanded while the commands are always deferred.

Table 3-1 summarizes what occurs when variables are expanded.

Definition

Expansion of a

Expansion of b

Immediate

Deferred

Immediate

Deferred

Immediate

Immediate

Immediate

Deferred or immediate

Immediate

Deferred

  

As a general rule, always define variables and macros before they are used. In particular, it is required that a variable used in a target or prerequisite be defined before its use.

An example will make all this clearer. Suppose we reimplement our free-space macro. We’ll go over the example a piece at a time, then put them all together at the end.

We define three variables to hold the names of the programs we use in our macro. To avoid code duplication we factor out the bin directory into a fourth variable. The four variable definitions are read and their righthand sides are immediately expanded because they are simple variables. Because BIN is defined before the others, its value can be plugged into their values.

Next, we define the free-space macro.

The define directive is followed by a variable name that is immediately expanded. In this case, no expansion is necessary. The body of the macro is read and stored unexpanded.

Finally, we use our macro in a rule.

When $(OUTPUT_DIR)/very_big_file is read, any variables used in the targets and prerequisites are immediately expanded. Here, $(OUTPUT_DIR) is expanded to /tmp to form the /tmp/very_big_file target. Next, the command script for this target is read. Command lines are recognized by the leading tab character and are read and stored, but not expanded.

Here is the entire example makefile . The order of elements in the file has been scrambled intentionally to illustrate make ’s evaluation algorithm.

Notice that although the order of lines in the makefile seems backward, it executes just fine. This is one of the surprising effects of recursive variables. It can be immensely useful and confusing at the same time. The reason this makefile works is that expansion of the command script and the body of the macro are deferred until they are actually used. Therefore, the relative order in which they occur is immaterial to the execution of the makefile .

In the second phase of processing, after the makefile is read, make identifies the targets, performs dependency analysis, and executes the actions for each rule. Here the only target, $(OUTPUT_DIR)/very_big_file , has no prerequisites, so make will simply execute the actions (assuming the file doesn’t exist). The command is $(free-space) . So make expands this as if the programmer had written:

Once all variables are expanded, it begins executing commands one at a time.

Let’s look at the two parts of the makefile where the order is important. As explained earlier, the target $(OUTPUT_DIR)/very_big_file is expanded immediately. If the definition of the variable OUTPUT_DIR had followed the rule, the expansion of the target would have yielded /very_big_file . Probably not what the user wanted. Similarly, if the definition of BIN had been moved after AWK , those three variables would have expanded to /printf , /df , and /awk because the use of := causes immediate evaluation of the righthand side of the assignment. However, in this case, we could avoid the problem for PRINTF , DF , and AWK by changing := to = , making them recursive variables. One last detail. Notice that changing the definitions of OUTPUT_DIR and BIN to recursive variables would not change the effect of the previous ordering problems. The important issue is that when $(OUTPUT_DIR)/very_big_file and the righthand sides of PRINTF , DF , and AWK are expanded, their expansion happens immediately, so the variables they refer to must be already defined.

Target- and Pattern-Specific Variables

Variables usually have only one value during the execution of a makefile . This is ensured by the two-phase nature of makefile processing. In phase one, the makefile is read, variables are assigned and expanded, and the dependency graph is built. In phase two, the dependency graph is analyzed and traversed. So when command scripts are being executed, all variable processing has already completed. But suppose we wanted to redefine a variable for just a single rule or pattern.

In this example, the particular file we are compiling needs an extra command-line option, -DUSE_NEW_MALLOC=1 , that should not be provided to other compiles:

Here, we’ve solved the problem by duplicating the compilation command script and adding the new required option. This approach is unsatisfactory in several respects. First, we are duplicating code. If the rule ever changes or if we choose to replace the built-in rule with a custom pattern rule, this code would need to be updated and we might forget. Second, if many files require special treatment, the task of pasting in this code will quickly become very tedious and error-prone (imagine a hundred files like this).

To address this issue and others, make provides target-specific variables . These are variable definitions attached to a target that are valid only during the processing of that target and any of its prerequisites. We can rewrite our previous example using this feature like this:

The variable CPPFLAGS is built in to the default C compilation rule and is meant to contain options for the C preprocessor. By using the += form of assignment, we append our new option to any existing value already present. Now the compile command script can be removed entirely:

While the gui.o target is being processed, the value of CPPFLAGS will contain -DUSE_ NEW_MALLOC=1 in addition to its original contents. When the gui.o target is finished, CPPFLAGS will revert to its original value. Pattern-specific variables are similar, only they are specified in a pattern rule (see Pattern Rules ).

The general syntax for target-specific variables is:

As you can see, all the various forms of assignment are valid for a target-specific variable. The variable does not need to exist before the assignment.

Furthermore, the variable assignment is not actually performed until the processing of the target begins. So the righthand side of the assignment can itself be a value set in another target-specific variable. The variable is valid during the processing of all prerequisites as well.

Where Variables Come From

So far, most variables have been defined explicitly in our own makefile s, but variables can have a more complex ancestry. For instance, we have seen that variables can be defined on the make command line. In fact, make variables can come from these sources:

Of course, variables can be defined in the makefile or a file included by the makefile (we’ll cover the include directive shortly).

Variables can be defined or redefined directly from the make command line:

A command-line argument containing an = is a variable assignment. Each variable assignment on the command line must be a single shell argument. If the value of the variable (or heaven forbid, the variable itself) contains spaces, the argument must be surrounded by quotes or the spaces must be escaped.

An assignment of a variable on the command line overrides any value from the environment and any assignment in the makefile . Command-line assignments can set either simple or recursive variables by using := or = , respectively. It is possible using the override directive to allow a makefile assignment to be used instead of a command-line assignment.

Of course, you should ignore a user’s explicit assignment request only under the most urgent circumstances (unless you just want to irritate your users).

All the variables from your environment are automatically defined as make variables when make starts. These variables have very low precedence, so assignments within the makefile or command-line arguments will override the value of an environment variable. You can cause environment variables to override makefile variables using the --environment-overrides (or -e ) command-line option.

When make is invoked recursively, some variables from the parent make are passed through the environment to the child make . By default, only those variables that originally came from the environment are exported to the child’s environment, but any variable can be exported to the environment by using the export directive:

You can cause all variables to be exported with:

Note that make will export even those variables whose names contain invalid shell variable characters. For example:

An “invalid” shell variable was created by exporting valid-variable-in-make . This variable is not accessible through normal shell syntax, only through trickery such as running grep over the environment. Nevertheless, this variable is inherited by any sub- make where it is valid and accessible. We will cover use of “recursive” make in Part II .

You can also prevent an environment variable from being exported to the subprocess:

The mp_export and mp_unexport directives work the same way the mp_sh commands mp_export and mp_unset work.

The conditional assignment operator interacts very nicely with environment variables. Suppose you have a default output directory set in your makefile , but you want users to be able to override the default easily. Conditional assignment is perfect for this situation:

Here the assignment is performed only if OUTPUT_DIR has never been set. We can get nearly the same effect more verbosely with:

The difference is that the conditional assignment operator will skip the assignment if the variable has been set in any way, even to the empty value, while the ifdef and ifndef operators test for a nonempty value. Thus, OUTPUT_DIR= is considered set by the conditional operator but not defined by ifdef .

It is important to note that excessive use of environment variables makes your makefile s much less portable, since other users are not likely to have the same set of environment variables. In fact, I rarely use this feature for precisely that reason.

Finally, make creates automatic variables immediately before executing the command script of a rule.

Traditionally, environment variables are used to help manage the differences between developer machines. For instance, it is common to create a development environment (source code, compiled output tree, and tools) based on environment variables referenced in the makefile . The makefile would refer to one environment variable for the root of each tree. If the source file tree is referenced from a variable PROJECT_SRC , binary output files from PROJECT_BIN , and libraries from PROJECT_LIB , then developers are free to place these trees wherever is appropriate.

A potential problem with this approach (and with the use of environment variables in general) occurs when these “root” variables are not set. One solution is to provide default values in the makefile using the ?= form of assignment:

By using these variables to access project components, you can create a development environment that is adaptable to varying machine layouts. (We will see more comprehensive examples of this in Part II .) Beware of overreliance on environment variables, however. Generally, a makefile should be able to run with a minimum of support from the developer’s environment so be sure to provide reasonable defaults and check for the existence of critical components.

Conditional and include Processing

Parts of a makefile can be omitted or selected while the makefile is being read using conditional processing directives. The condition that controls the selection can have several forms such as “is defined” or “is equal to.” For example:

This selects the first branch of the conditional if the variable COMSPEC is defined.

The basic syntax of the conditional directive is:

The if-condition can be one of:

The variable-name should not be surrounded by $( ) for the ifdef / ifndef test. Finally, the test can be expressed as either of:

in which single or double quotes can be used interchangeably (but the quotes you use must match).

The conditional processing directives can be used within macro definitions and command scripts as well as at the top level of makefile s:

I like to indent my conditionals, but careless indentation can lead to errors. In the preceding lines, the conditional directives are indented four spaces while the enclosed commands have a leading tab. If the enclosed commands didn’t begin with a tab, they would not be recognized as commands by make . If the conditional directives had a leading tab, they would be misidentified as commands and passed to the subshell.

The ifeq and ifneq conditionals test if their arguments are equal or not equal. Whitespace in conditional processing can be tricky to handle. For instance, when using the parenthesis form of the test, whitespace after the comma is ignored, but all other whitespace is significant:

Personally, I stick with the quoted forms of equality:

Even so, it often occurs that a variable expansion contains unexpected whitespace. This can cause problems since the comparison includes all characters. To create more robust makefile s, use the strip function:

The include Directive

We first saw the include directive in Chapter 2 , in the section Automatic Dependency Generation . Now let’s go over it in more detail.

A makefile can include other files. This is most commonly done to place common make definitions in a make header file or to include automatically generated dependency information. The include directive is used like this:

The directive can be given any number of files and shell wildcards and make variables are also allowed.

include and Dependencies

When make encounters an include directive, it expands the wildcards and variable references, then tries to read the include file. If the file exists, we continue normally. If the file does not exist, however, make reports the problem and continues reading the rest of the makefile . When all reading is complete, make looks in the rules database for any rule to update the include files. If a match is found, make follows the normal process for updating a target. If any of the include files is updated by a rule, make then clears its internal database and rereads the entire makefile . If, after completing the process of reading, updating, and rereading, there are still include directives that have failed due to missing files, make terminates with an error status.

We can see this process in action with the following two-file example. We use the warning built-in function to print a simple message from make . (This and other functions are covered in detail in Chapter 4 .) Here is the makefile :

and here is bar.mk , the source for the included file:

When run, we see:

The first line shows that make cannot find the include file, but the second line shows that make keeps reading and executing the makefile . After completing the read, make discovers a rule to create the include file, foo.mk , and it does so. Then make starts the whole process again, this time without encountering any difficulty reading the include file.

Now is a good time to mention that make will also treat the makefile itself as a possible target. After the entire makefile has been read, make will look for a rule to remake the currently executing makefile . If it finds one, make will process the rule, then check if the makefile has been updated. If so, make will clear its internal state and reread the makefile , performing the whole analysis over again. Here is a silly example of an infinite loop based on this behavior:

When make executes this makefile , it sees that the makefile is out of date (because the .PHONY target, dummy , is out of date) so it executes the touch command, which updates the timestamp of the makefile . Then make rereads the file and discovers that the makefile is out of date....Well, you get the idea.

Where does make look for included files? Clearly, if the argument to include is an absolute file reference, make reads that file. If the file reference is relative, make first looks in its current working directory. If make cannot find the file, it then proceeds to search through any directories you have specified on the command line using the --include-dir (or -I ) option. After that, make searches a compiled search path similar to: /usr/local/include , /usr/gnu/include , /usr/include . There may be slight variations of this path due to the way make was compiled.

If make cannot find the include file and it cannot create it using a rule, make exits with an error. If you want make to ignore include files it cannot load, add a leading dash to the include directive:

For compatibility with other make s, the word sinclude is an alias for -include .

It is worth noting that using an include directive before the first target in a makefile might change the default goal. That is, if the include file contains any targets at all the first of those targets will become the default goal for the makefile. This can be avoided by simply placing the desired default goal before the include (even without prerequisites or targets):

Standard make Variables

In addition to automatic variables, make maintains variables revealing bits and pieces of its own state as well as variables for customizing built-in rules:

This is the version number of GNU make . At the time of this writing, its value is 3.80 , and the value in the CVS repository is 3.81rc1 .

The previous version of make , 3.79.1, did not support the eval and value functions (among other changes) and it is still very common. So when I write makefile s that require these features, I use this variable to test the version of make I’m running. We’ll see an example of that in the section Flow Control in Chapter 4 .

This variable contains the current working directory (cwd) of the executing make process. This will be the same directory the make program was executed from (and it will be the same as the shell variable PWD ), unless the --directory ( -C ) option is used. The --directory option instructs make to change to a different directory before searching for any makefile . The complete form of the option is --directory= directory-name or -C directory-name . If --directory is used, CURDIR will contain the directory argument to --include-dir .

I typically invoke make from emacs while coding. For instance, my current project is in Java and uses a single makefile in a top-level directory (not necessarily the directory containing the code). In this case, using the --directory option allows me to invoke make from any directory in the source tree and still access the makefile . Within the makefile , all paths are relative to the makefile directory. Absolute paths are occasionally required and these are accessed using CURDIR .

This variable contains a list of each file make has read including the default makefile and makefile s specified on the command line or through include directives. Just before each file is read, the name is appended to the MAKEFILE_LIST variable. So a makefile can always determine its own name by examining the last word of the list.

The MAKECMDGOALS variable contains a list of all the targets specified on the command line for the current execution of make . It does not include command-line options or variable assignments. For instance:

The example uses the “trick” of telling make to read the makefile from the stdin with the -f- (or --file ) option. The stdin is redirected from a command-line string using bash ’s here string , “<<<”, syntax. [ 6 ] The makefile itself consists of the default goal goal , while the command script is given on the same line by separating the target from the command with a semicolon. The command script contains the single line:

MAKECMDGOALS is typically used when a target requires special handling. The primary example is the “clean” target. When invoking “clean,” make should not perform the usual dependency file generation triggered by include (discussed in the section Automatic Dependency Generation in Chapter 2 ). To prevent this use ifneq and MAKECMDGOALS :

This contains a list of the names of all the variables defined in makefile s read so far, with the exception of target-specific variables. The variable is read-only and any assignment to it is ignored.

As you’ve seen, variables are also used to customize the implicit rules built in to make . The rules for C/C++ are typical of the form these variables take for all programming languages. Figure 3-1 shows the variables controlling translation from one file type to another.

Variables for C/C++ compilation

The variables have the basic form: ACTION . suffix . The ACTION is COMPILE for creating an object file, LINK for creating an executable, or the “special” operations PREPROCESS , YACC , LEX for running the C preprocessor, yacc , or lex , respectively. The suffix indicates the source file type.

The standard “path” through these variables for, say, C++, uses two rules. First, compile C++ source files to object files. Then link the object files into an executable.

The first rule uses these variable definitions:

GNU make supports either of the suffixes .C or .cc for denoting C++ source files. The CXX variable indicates the C++ compiler to use and defaults to g++ . The variables CXXFLAGS , CPPFLAGS , and TARGET_ARCH have no default value. They are intended for use by end-users to customize the build process. The three variables hold the C++ compiler flags, C preprocessor flags, and architecture-specific compilation options, respectively. The OUTPUT_OPTION contains the output file option.

The linking rule is a bit simpler:

This rule uses the C compiler to combine object files into an executable. The default for the C compiler is gcc . LDFLAGS and TARGET_ARCH have no default value. The LDFLAGS variable holds options for linking such as -L flags. The LOADLIBES and LDLIBS variables contain lists of libraries to link against. Two variables are included mostly for portability.

This was a quick tour through the make variables. There are more, but this gives you the flavor of how variables are integrated with rules. Another group of variables deals with TEX and has its own set of rules. Recursive make is another feature supported by variables. We’ll discuss this topic in Chapter 6 .

[ 4 ] The df command returns a list of each mounted filesystem and statistics on the filesystem’s capacity and usage. With an argument, it prints statistics for the specified filesystem. The first line of the output is a list of column titles. This output is read by awk which examines the second line and ignores all others. Column four of df ’s output is the remaining free space in blocks.

[ 5 ] For best effect here, the RM variable should be defined to hold rm -rf . In fact, its default value is rm -f , safer but not quite as useful. Further, MKDIR should be defined as mkdir -p , and so on.

[ 6 ] For those of you who want to run this type of example in another shell, use:

Get Managing Projects with GNU Make, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

make conditional assignment

TutorialsTonight Logo

Python Conditional Assignment

When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

In this tutorial, we will look at different ways to assign values to a variable based on some condition.

1. Using Ternary Operator

The ternary operator is very special operator in Python, it is used to assign a value to a variable based on some condition.

It goes like this:

Here, the value of variable will be value_if_true if the condition is true, else it will be value_if_false .

Let's see a code snippet to understand it better.

You can see we have conditionally assigned a value to variable c based on the condition a > b .

2. Using if-else statement

if-else statements are the core part of any programming language, they are used to execute a block of code based on some condition.

Using an if-else statement, we can assign a value to a variable based on the condition we provide.

Here is an example of replacing the above code snippet with the if-else statement.

3. Using Logical Short Circuit Evaluation

Logical short circuit evaluation is another way using which you can assign a value to a variable conditionally.

The format of logical short circuit evaluation is:

It looks similar to ternary operator, but it is not. Here the condition and value_if_true performs logical AND operation, if both are true then the value of variable will be value_if_true , or else it will be value_if_false .

Let's see an example:

But if we make condition True but value_if_true False (or 0 or None), then the value of variable will be value_if_false .

So, you can see that the value of c is 20 even though the condition a < b is True .

So, you should be careful while using logical short circuit evaluation.

While working with lists , we often need to check if a list is empty or not, and if it is empty then we need to assign some default value to it.

Let's see how we can do it using conditional assignment.

Here, we have assigned a default value to my_list if it is empty.

Assign a value to a variable conditionally based on the presence of an element in a list.

Now you know 3 different ways to assign a value to a variable conditionally. Any of these methods can be used to assign a value when there is a condition.

The cleanest and fastest way to conditional value assignment is the ternary operator .

if-else statement is recommended to use when you have to execute a block of code based on some condition.

Happy coding! 😊

?: conditional operator in Verilog

Compact conditional operators.

Many Verilog designs make use of a compact conditional operator:

A comman example, shown below, is an “enable” mask. Suppose there is some internal signal named a . When enabled by en== 1 , the module assigns q = a , otherwise it assigns q = 0 :

The syntax is also permitted in always blocks:

Assigned Tasks

This assignment uses only a testbench simulation, with no module to implement. Open the file src/testbench.v and examine how it is organized. It uses the conditional operator in an always block to assign q = a^b (XOR) when enabled, else q= 0 .

Run make simulate to test the operation. Verify that the console output is correct. Then modify the testbench to use an assign statement instead of an always block . Change the type of q as appropriate for the assign statement.

Turn in your work using git :

Indicate on Canvas that your assignment is done.

Next: Functions , Previous: Using Variables , Up: Top   [ Contents ][ Index ]

7 Conditional Parts of Makefiles

A conditional directive causes part of a makefile to be obeyed or ignored depending on the values of variables. Conditionals can compare the value of one variable to another, or the value of a variable to a constant string. Conditionals control what make actually “sees” in the makefile, so they cannot be used to control recipes at the time of execution.

  Example of a conditional
  The syntax of conditionals.
  Conditionals that test flags.

Next: Conditional Syntax , Previous: Conditionals , Up: Conditionals   [ Contents ][ Index ]

7.1 Example of a Conditional

The following example of a conditional tells make to use one set of libraries if the CC variable is ‘ gcc ’, and a different set of libraries otherwise. It works by controlling which of two recipe lines will be used for the rule. The result is that ‘ CC=gcc ’ as an argument to make changes not only which compiler is used but also which libraries are linked.

This conditional uses three directives: one ifeq , one else and one endif .

The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared. The lines of the makefile following the ifeq are obeyed if the two arguments match; otherwise they are ignored.

The else directive causes the following lines to be obeyed if the previous conditional failed. In the example above, this means that the second alternative linking command is used whenever the first alternative is not used. It is optional to have an else in a conditional.

The endif directive ends the conditional. Every conditional must end with an endif . Unconditional makefile text follows.

As this example illustrates, conditionals work at the textual level: the lines of the conditional are treated as part of the makefile, or ignored, according to the condition. This is why the larger syntactic units of the makefile, such as rules, may cross the beginning or the end of the conditional.

When the variable CC has the value ‘ gcc ’, the above example has this effect:

When the variable CC has any other value, the effect is this:

Equivalent results can be obtained in another way by conditionalizing a variable assignment and then using the variable unconditionally:

Next: Testing Flags , Previous: Conditional Example , Up: Conditionals   [ Contents ][ Index ]

7.2 Syntax of Conditionals

The syntax of a simple conditional with no else is as follows:

The text-if-true may be any lines of text, to be considered as part of the makefile if the condition is true. If the condition is false, no text is used instead.

The syntax of a complex conditional is as follows:

There can be as many “ else conditional-directive ” clauses as necessary. Once a given condition is true, text-if-true is used and no other clause is used; if no condition is true then text-if-false is used. The text-if-true and text-if-false can be any number of lines of text.

The syntax of the conditional-directive is the same whether the conditional is simple or complex; after an else or not. There are four different directives that test different conditions. Here is a table of them:

Expand all variable references in arg1 and arg2 and compare them. If they are identical, the text-if-true is effective; otherwise, the text-if-false , if any, is effective.

Often you want to test if a variable has a non-empty value. When the value results from complex expansions of variables and functions, expansions you would consider empty may actually contain whitespace characters and thus are not seen as empty. However, you can use the strip function (see Text Functions ) to avoid interpreting whitespace as a non-empty value. For example:

will evaluate text-if-empty even if the expansion of $(foo) contains whitespace characters.

Expand all variable references in arg1 and arg2 and compare them. If they are different, the text-if-true is effective; otherwise, the text-if-false , if any, is effective.

The ifdef form takes the name of a variable as its argument, not a reference to a variable. If the value of that variable has a non-empty value, the text-if-true is effective; otherwise, the text-if-false , if any, is effective. Variables that have never been defined have an empty value. The text variable-name is expanded, so it could be a variable or function that expands to the name of a variable. For example:

The variable reference $(foo) is expanded, yielding bar , which is considered to be the name of a variable. The variable bar is not expanded, but its value is examined to determine if it is non-empty.

Note that ifdef only tests whether a variable has a value. It does not expand the variable to see if that value is nonempty. Consequently, tests using ifdef return true for all definitions except those like foo = . To test for an empty value, use ifeq ($(foo),) . For example,

sets ‘ frobozz ’ to ‘ yes ’, while:

sets ‘ frobozz ’ to ‘ no ’.

If the variable variable-name has an empty value, the text-if-true is effective; otherwise, the text-if-false , if any, is effective. The rules for expansion and testing of variable-name are identical to the ifdef directive.

Extra spaces are allowed and ignored at the beginning of the conditional directive line, but a tab is not allowed. (If the line begins with a tab, it will be considered part of a recipe for a rule.) Aside from this, extra spaces or tabs may be inserted with no effect anywhere except within the directive name or within an argument. A comment starting with ‘ # ’ may appear at the end of the line.

The other two directives that play a part in a conditional are else and endif . Each of these directives is written as one word, with no arguments. Extra spaces are allowed and ignored at the beginning of the line, and spaces or tabs at the end. A comment starting with ‘ # ’ may appear at the end of the line.

Conditionals affect which lines of the makefile make uses. If the condition is true, make reads the lines of the text-if-true as part of the makefile; if the condition is false, make ignores those lines completely. It follows that syntactic units of the makefile, such as rules, may safely be split across the beginning or the end of the conditional.

make evaluates conditionals when it reads a makefile. Consequently, you cannot use automatic variables in the tests of conditionals because they are not defined until recipes are run (see Automatic Variables ).

To prevent intolerable confusion, it is not permitted to start a conditional in one makefile and end it in another. However, you may write an include directive within a conditional, provided you do not attempt to terminate the conditional inside the included file.

Previous: Conditional Syntax , Up: Conditionals   [ Contents ][ Index ]

7.3 Conditionals that Test Flags

You can write a conditional that tests make command flags such as ‘ -t ’ by using the variable MAKEFLAGS together with the findstring function (see Functions for String Substitution and Analysis ). This is useful when touch is not enough to make a file appear up to date.

The findstring function determines whether one string appears as a substring of another. If you want to test for the ‘ -t ’ flag, use ‘ t ’ as the first string and the value of MAKEFLAGS as the other.

For example, here is how to arrange to use ‘ ranlib -t ’ to finish marking an archive file up to date:

The ‘ + ’ prefix marks those recipe lines as “recursive” so that they will be executed despite use of the ‘ -t ’ flag. See Recursive Use of make .

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Conditional Statements in Python

Understanding and mastering Python’s conditional statements is fundamental for any programmer aspiring to write efficient and robust code. In this guide, we’ll delve into the intricacies of conditional statements in Python, covering the basics, advanced techniques, and best practices.

  • What are Conditional Statements?

Conditional Statements are statements in Python that provide a choice for the control flow based on a condition. It means that the control flow of the Python program will be decided based on the outcome of the condition. Now let us see how Conditional Statements are implemented in Python.

  • Types of Conditional Statements in Python

1. If Conditional Statement in Python

2. if else conditional statements in python, 3. nested if..else conditional statements in python, 4. if-elif-else conditional statements in python, 5. ternary expression conditional statements in python, best practices for using conditional statements.

If the simple code of block is to be performed if the condition holds then the if statement is used. Here the condition mentioned holds then the code of the block runs otherwise not.

Syntax of If Statement :

In a conditional if Statement the additional block of code is merged as an else statement which is performed when if condition is false. 

Syntax of Python If-Else : 

Nested if..else means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if – else statement is present and such type of statement is known as nested if statement. We can use one if or else if statement inside another if or else if statements.

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final “else” statement will be executed.

The Python ternary Expression determines if a condition is true or false and then returns the appropriate value in accordance with the result. The ternary Expression is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.

Syntax of Ternary Expression

  • Keep conditions simple and expressive for better readability.
  • Avoid deeply nested conditional blocks; refactor complex logic into smaller, more manageable functions.
  • Comment on complex conditions to clarify their purpose.
  • Prefer the ternary operator for simple conditional assignments.
  • Advanced Techniques:
  • Using short-circuit evaluation for efficiency in complex conditions.
  • Leveraging the any() and all() functions with conditions applied to iterables.
  • Employing conditional expressions within list comprehensions and generator expressions.

Conditional Statements in Python – FAQs

What are conditional statements in python.

Conditional statements in Python are used to execute a specific block of code based on the truth value of a condition. The most common conditional statements in Python are if , elif , and else . These allow the program to react differently depending on whether a condition (or a series of conditions) is true or false. x = 10 if x > 5: print("x is greater than 5") elif x == 5: print("x is equal to 5") else: print("x is less than 5")

What is a Conditional Expression in Python?

A conditional expression (also known as a ternary operator) in Python provides a method to simplify conditional statements. It allows for a quick definition of a condition and two possible outcomes (one if the condition is true, and one if the condition is false). The syntax is value_if_true if condition else value_if_false . # Conditional expression example x = 5 result = "High" if x > 10 else "Low" print(result) # Outputs: "Low"

What are Decision-Making Statements in Python?

Decision-making statements in Python help to control the flow of execution based on certain conditions. These include: if statement: Executes a block of code if a specified condition is true. if-else statement: Executes one block of code if the condition is true, and another block if the condition is false. elif (else if) statement: Checks multiple conditions in a sequence and executes a block of code as soon as one of the conditions evaluates to true. Nested if statements: You can nest if statements within another if or else block to create complex decision trees.

What are Conditional Selection Statements in Python?

Conditional selection statements refer to the use of if , elif , and else statements that select specific blocks of code to execute based on conditions. These statements are fundamental for branching in programming, allowing different outcomes depending on the input or state of the program.

What are the Conditional Loops in Python?

While Python supports loops that can incorporate conditions, the term “conditional loops” might specifically refer to loops that run based on a condition. Python provides two primary types of such loops: while loop: Continues to execute as long as a given condition is true. It checks the condition before executing the loop body. # while loop example x = 5 while x < 10: print(x) x += 1 for loop: Iterates over a sequence (like a list, tuple, or string) and executes the loop body for each item in the sequence. Although not traditionally a “conditional” loop, it can incorporate conditions using break and continue to control the loop execution dynamically. # for loop example with condition for i in range(10): if i == 5: break # Exit the loop when i is 5 print(i) These explanations outline how Python uses conditional statements and expressions to manage the flow of execution and make decisions within programs, crucial for creating dynamic and responsive applications

Please Login to comment...

Similar reads.

  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

GitHub

Verilog Conditional Operator

Just what the heck is that question mark doing.

Have you ever come across a strange looking piece of Verilog code that has a question mark in the middle of it? A question mark in the middle of a line of code looks so bizarre; they’re supposed to go at the end of sentences! However in Verilog the ? operator is a very useful one, but it does take a bit of getting used to.

The question mark is known in Verilog as a conditional operator though in other programming languages it also is referred to as a ternary operator , an inline if , or a ternary if . It is used as a short-hand way to write a conditional expression in Verilog (rather than using if/else statements). Let’s look at how it is used:

Here, condition is the check that the code is performing. This condition might be things like, “Is the value in A greater than the value in B?” or “Is A=1?”. Depending on if this condition evaluates to true, the first expression is chosen. If the condition evaluates to false, the part after the colon is chosen. I wrote an example of this. The code below is really elegant stuff. The way I look at the question mark operator is I say to myself, “Tell me about the value in r_Check. If it’s true, then return “HI THERE” if it’s false, then return “POTATO”. You can also use the conditional operator to assign signals , as shown with the signal w_Test1 in the example below. Assigning signals with the conditional operator is useful!

Nested Conditional Operators

There are examples in which it might be useful to combine two or more conditional operators in a single assignment. Consider the truth table below. The truth table shows a 2-input truth table. You need to know the value of both r_Sel[1] and r_Sel[0] to determine the value of the output w_Out. This could be achieved with a bunch of if-else if-else if combinations, or a case statement, but it’s much cleaner and simpler to use the conditional operator to achieve the same goal.

r_Sel[1] r_Sel[0] Output w_Out
0 0 1
0 1 1
1 0 1
1 1 0

Learn Verilog

One Comment

' src=

The input “r_Sel” must be reg type? Could it be wire type?

Leave A Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Next: Conditional Variable Assignment , Previous: Simply Expanded Variable Assignment , Up: The Two Flavors of Variables   [ Contents ][ Index ]

6.2.3 Immediately Expanded Variable Assignment

Another form of assignment allows for immediate expansion, but unlike simple assignment the resulting variable is recursive: it will be re-expanded again on every use. In order to avoid unexpected results, after the value is immediately expanded it will automatically be quoted: all instances of $ in the value after expansion will be converted into $$ . This type of assignment uses the ‘ :::= ’ operator. For example,

results in the OUT variable containing the text ‘ first ’, while here:

results in the OUT variable containing the text ‘ one$$two ’. The value is expanded when the variable is assigned, so the result is the expansion of the first value of var , ‘ one$two ’; then the value is re-escaped before the assignment is complete giving the final result of ‘ one$$two ’.

The variable OUT is thereafter considered a recursive variable, so it will be re-expanded when it is used.

This seems functionally equivalent to the ‘ := ’ / ‘ ::= ’ operators, but there are a few differences:

First, after assignment the variable is a normal recursive variable; when you append to it with ‘ += ’ the value on the right-hand side is not expanded immediately. If you prefer the ‘ += ’ operator to expand the right-hand side immediately you should use the ‘ := ’ / ‘ ::= ’ assignment instead.

Second, these variables are slightly less efficient than simply expanded variables since they do need to be re-expanded when they are used, rather than merely copied. However since all variable references are escaped this expansion simply un-escapes the value, it won’t expand any variables or run any functions.

Here is another example:

After this, the value of OUT is the text ‘ one$$two $(var) ’. When this variable is used it will be expanded and the result will be ‘ one$two three$four ’.

This style of assignment is equivalent to the traditional BSD make ‘ := ’ operator; as you can see it works slightly differently than the GNU make ‘ := ’ operator. The :::= operator is added to the POSIX specification in Issue 8 to provide portability.

  • Twins Claim Cole Irvin
  • Matt Adams Announces Retirement
  • Tyler Glasnow “Highly Unlikely” To Return This Year Due To Elbow Sprain
  • Mets Promote Luisangel Acuña
  • Rangers Activate Jacob deGrom
  • Rangers Extend Chris Young
  • Hoops Rumors
  • Pro Football Rumors
  • Pro Hockey Rumors

MLB Trade Rumors

Marlins Designate Jonathan Bermudez For Assignment

By Steve Adams | September 12, 2024 at 2:37pm CDT

The Marlins announced a series of roster moves today, most notably designating lefty Jonathan Bermudez for assignment in order to clear roster space for righty Jeff Lindgren , whose contract has been selected from Triple-A Jacksonville. Miami also placed righty John McMillon on the 15-day injured list due to tightness in his right elbow. McMillon’s roster spot will be filled by righty Michael Petersen , whom the Fish claimed from the Dodgers earlier this week and who’ll now jump right onto the big league roster.

As Craig Mish of SportsGrid and the Miami Herald points out ( on X ), once either Lindgren or Petersen take the mound for the Marlins, the team will set a new major league record for most players used in a single season. They’re currently tied with the 2019 Mariners at 69 players. It’d be somewhat poetic if Petersen gets the distinction, as Miami announced he’ll wear No. 70 with the club.

Bermudez, 28, joined the Marlins on a minor league deal in April 2023. The former Astros draftee had been released by the Giants prior to that deal. He’s pitched 6 2/3 innings this season, his first career action at the MLB level, and allowed six runs on 11 hits and a pair of walks with four strikeouts. He’s had a rough showing in Jacksonville, too, logging a 6.46 ERA in 24 2/3 frames.

Bermudez has worked more in the bullpen this season than in years past. He spent the 2023 campaign in the Double-A rotation for the Marlins, where he made 18 starts and posted a 4.58 ERA in 94 1/3 innings. Bermudez punched out 26.6% of his opponents there against a 9.5% walk rate. The former 23rd-round pick (2018) briefly snuck onto the back end of Baseball America’s top-30 Astros prospects back in 2022, but he’s taken some steps back since that point.

Lindgren, 27, pitched seven innings for the Marlins last year in his MLB debut but was eventually removed from the 40-man roster. He’s been hit hard in the upper minors this year, combining for 75 2/3 innings of 6.19 ERA ball between Double-A and Triple-A.

Since he’s been working out of the Jacksonville rotation, he’s stretched out for multiple innings of relief if needed. The Marlins’ pitching staff is in shambles following injuries to Jesus Luzardo , Eury Perez , Braxton Garrett , Max Meyer , Ryan Weathers , Calvin Faucher and Andrew Nardi , among others (plus trades of Trevor Rogers , Tanner Scott , A.J. Puk , Bryan Hoeing , JT Chargois and Huascar Brazoban ). Lindgren can fill any role necessary down the stretch but will likely be removed from the 40-man once again at some point.

' src=

What’s next for this lad? Maybe a little vaycay to decompress? Where to? The West Indies? Bahamas, Cancun? Tahiti? Decisions.

' src=

Who would want to manage this team next year who has a proven record? No one. Only someone for their first ML Job. or someone who gets five years of guaranteed money!

' src=

@UWP 2025 Marlins will have a very good rotation and Bendix will have a Front Office he can trust. The Marlins are unlikely to contend next year, but could be very competitive.

Schumaker may well have decided he might like to manage this team next year. He is regularly saying nice things about the Front Office. Luis Urueta, Jon Jay and maybe Rod Barajas would be interested in taking the job on. From the Front Office Gabe Kapler or Rachel Balkovec might be interested

Thank You for your thoughtful answer!

Leave a Reply Cancel reply

Please login to leave a reply.

Log in Register

make conditional assignment

  • Feeds by Team
  • Commenting Policy
  • Privacy Policy

MLB Trade Rumors is not affiliated with Major League Baseball, MLB or MLB.com

FOX Sports Engage Network

Username or Email Address

Remember Me

free hit counter

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Python conditional assignment operator

Does a Python equivalent to the Ruby ||= operator ("set the variable if the variable is not set") exist?

Example in Ruby :

  • conditional-statements

the Tin Man's user avatar

  • 1 It doesn't set it if it's not set - it sets it if its current value is false ( false or nil ). Granted, this distinction is more important in languages that e.g. treat 0 and "" as false, but still –  user395760 Commented Jun 19, 2011 at 12:23
  • what is the use case for this ruby operator? –  David Heffernan Commented Jun 19, 2011 at 12:54
  • 1 The way to do it would be to use a try except NameError as indicated by phihag, butthis does not make myuch sense in Python as stated by everyone here. In Ruby it is more usefull due to the way people do pass arbitrary code blocks to be run inside a function. The target function than might need to set a variable that was not initialized in the foreign block it executed. There are no such cases in Python. –  jsbueno Commented Jun 19, 2011 at 19:45

10 Answers 10

I'm surprised no one offered this answer. It's not as "built-in" as Ruby's ||= but it's basically equivalent and still a one-liner:

Of course, locals() is just a dictionary, so you can do:

Keith Devens's user avatar

I would use

Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need None , 0 , False , or "" to be valid values however, you will need to change this behavior, for instance:

This sort of thing is also just begging to be turned into a function you can use everywhere easily:

at which point, you can use it as:

Finally, if you are really missing your Ruby infix notation, you could overload ||=| (or something similar) by following this guy's hack: http://code.activestate.com/recipes/384122-infix-operators/

emish's user avatar

  • 7 Your first example doesn't work: >>> x = 'default' if not x else x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined –  J Jones Commented Jan 30, 2015 at 23:06
  • 10 This is an incorrect answer, and will fail if x does not exist. Since the question asks for a way to test for existance, this solution will not work. –  Shayne Commented Mar 29, 2016 at 8:47
  • 2 This answer solved the problem "conditional assignment". set a variable if it was not set. of course, everything on the right must be defined, else you will get an error (I just took it as a pseudo-code). x = "value1" if True else "value2" . in general. x = 'value1' if condition else 'value2' –  Maubeh Commented Jan 6, 2019 at 14:54
  • This answer is both valid and very useful, and educational to boot. I would suggest a note be added that the variable must exist -within- the answer text, but fantastic otherwise. –  Danin Commented Jun 19, 2022 at 0:00

No, the replacement is:

However, wanting to use this construct is a sign of overly complicated code flow. Usually, you'd do the following:

and never be unsure whether v is set or not. If it's one of many options that can either be set or not, use a dictionary and its get method which allows a default value.

phihag's user avatar

  • 2 No, you don't use except: . –  user395760 Commented Jun 19, 2011 at 12:33
  • @delnan I didn't want to make specific assumptions about the nature of complicated() . Added it. –  phihag Commented Jun 19, 2011 at 12:35
  • You sure? @emish offers a much simpler solution. –  Donal Lafferty Commented Dec 17, 2012 at 16:39
  • That's a bad solution. Not only is it more complicated, but it's also much worse performance-wise. I would go as far as suggest to remove this solution from the question. –  yuvalm2 Commented Mar 19, 2021 at 14:02
  • Using a try . . .except for control flow is bad practice. An exception should be used when something is wrong not when trying to assign a variable. –  Paul D. Commented Nov 7, 2022 at 20:33

There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it:

For further reference, check out the Python 2.5 docs .

mainas's user avatar

  • This is not what is being asked for. –  Shayne Commented Mar 29, 2016 at 8:49
  • So for the question being asked: variable = "bla bla" if not variable else variable –  D. Ror. Commented Nov 7, 2023 at 14:08

(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:

to be correct in all contexts.

However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:

The exception method is probably closest analog.

Jas's user avatar

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

Jochen Ritzel's user avatar

I usually do this the following way:

Dog eat cat world's user avatar

I do this... just sharing in case it's useful for the OP or anyone else...

E_net4's user avatar

I think what you are looking for, if you are looking for something in a dictionary, is the setdefault method:

*** KeyError: 'q2' (Pdb)

The important thing to note in my example is that the setdefault method changes the dictionary if and only if the key that the setdefault method refers to is not present.

Jeff Silverman's user avatar

I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError . (see here, that Python has "names" , not variables...).

As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

Nevertheless, if your variable "exists", but has some sort of dummy value, like None , the following would work :

(see this paragraph about Truth Values )

tsimbalar's user avatar

  • 2 This breaks as soon as the value might be 0, "", an empty string, or anything else that's "falsy". Explicitly check whether it is None . –  user395760 Commented Jun 19, 2011 at 12:46
  • Oh yes, you are right, I hadn't thought of that. Thanks for the hint ! I have actually never had the need to do this "or" thing, and I thought it was a valid answer to the question ... but the question itself does not seem to be relevqnt to Python anyway ... –  tsimbalar Commented Jun 19, 2011 at 12:47

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python variables conditional-statements or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Counting the number of meetings
  • Fifth year PhD student with no progress on my thesis because of advisor, what to do?
  • Is internal energy depended on the acceleration of the system?
  • Alice splits the bill not too generously with Bob
  • How to use js in carousel code into a functional Next.js component for scrolling support in headless sitecore
  • On Concordant Readings in Titrations
  • Emergency belt repair
  • Is it possible/recommended to paint the side of piano's keys?
  • On Putting Parentheses Around Item Numbers with Enumitem
  • How can we speed up the process of returning our lost luggage?
  • Bitcoin Core 28 Tests (testmempoolaccept rejected but submitpackage accepted)
  • Has Macron's new government indicated whether it is "leaning" hard left or hard right?
  • My math professor is Chinese. Is it okay for me to speak Chinese to her in office hours?
  • How can I calculate derivative of eigenstates numerically?
  • Annoying query "specify CRS for layer World Map" in latest QGIS versions
  • Would Dicyanoacetylene Make a Good Flamethrower Fuel?
  • Cutting a curve through a thick timber without waste
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • Craig interpolants for Linear Temporal Logic: finding one when they exist
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • Missed the application deadline for a TA job. Should I contact them?
  • Can noun phrase have only one word?
  • Help with understanding a rigid geometry proof
  • Would a scientific theory of everything be falsifiable?

make conditional assignment

IMAGES

  1. Conditional Assignment

    make conditional assignment

  2. SOLUTION: Assignment b ppp grammar lesson table first conditional

    make conditional assignment

  3. Conditional Assignment

    make conditional assignment

  4. Create conditional formulas

    make conditional assignment

  5. PPT

    make conditional assignment

  6. How to Teach the First Conditional to ESL Students

    make conditional assignment

VIDEO

  1. Conditional and selected signal assignment statements

  2. Conditionals || Lecture 2|| Possible Conditional sentences|| LLB Part 2 English || English Grammar||

  3. Operators in C

  4. Conditional Sentences (Present Tense)

  5. Tips for writing College Assignment

  6. Conditionals || Type 3|| Past Hypothetical Conditional sentences|| LLB Part 2 English || Lecture 4

COMMENTS

  1. The Conditional Variable Assignment Operator in a Makefile

    To make it dynamic, let's include the login username in the message so that the greeting is more personalized for each user. Let's define a user variable and initialize it with the output of the whoami command by using the assignment (=) operator: user= $(shell whoami) We should note that we followed a standard naming convention of using ...

  2. Conditional Assignment (GNU make)

    There is another assignment operator for variables, '?= '. This is called a conditional variable assignment operator, because it only has an effect if the variable is not yet defined.

  3. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...

  4. Conditional Syntax (GNU make)

    Conditionals affect which lines of the makefile make uses. If the condition is true, make reads the lines of the text-if-true as part of the makefile; if the condition is false, make ignores those lines completely. It follows that syntactic units of the makefile, such as rules, may safely be split across the beginning or the end of the conditional.

  5. GNU Make

    Conditional Parts of Makefiles. A conditional causes part of a makefile to be obeyed or ignored depending on the values of variables. Conditionals can compare the value of one variable to another, or the value of a variable to a constant string. Conditionals control what make actually "sees" in the makefile, so they cannot be used to control ...

  6. Conditionals (GNU make)

    Conditionals can compare the value of one variable to another, or the value of a variable to a constant string. Conditionals control what make actually "sees" in the makefile, so they cannot be used to control recipes at the time of execution. Example of a Conditional. Syntax of Conditionals. Conditionals that Test Flags.

  7. 3. Variables and Macros

    The difference is that the conditional assignment operator will skip the assignment if the variable has been set in any way, even to the empty value, while the ifdef and ifndef operators test for a nonempty value.

  8. GNU make

    GNU make - How to Use Variables. Go to the first, previous, next, last section, table of contents. How to Use Variables. A variable is a name defined in a makefile to represent a string of text, called the variable's value. These values are substituted by explicit request into targets, prerequisites, commands, and other parts of the makefile.

  9. Python Conditional Assignment (in 3 Ways)

    Python Conditional Assignment When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

  10. Conditional Example (GNU make)

    Learn how to use conditional statements in GNU make with a practical example. Compare with the conditional syntax and master the logic.

  11. How to assign a variable in an IF condition, and then return it?

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (isBig(y)) as a variable (x) in order to re-use it within the body of the condition: if x := isBig(y): return x. edited Jan 8, 2023 at 14:33. answered Apr 27, 2019 at 15:37. Xavier Guihot. 60.4k 24 310 198.

  12. Conditional Statements in Programming

    In programming, the term "conditional statements" typically refers to constructs used to perform different actions based on whether a certain condition evaluates to true or false. The most common conditional statements are: If statement: Executes a block of code if a specified condition is true.

  13. ?: conditional operator in Verilog

    Assigned Tasks This assignment uses only a testbench simulation, with no module to implement. Open the file src/testbench.v and examine how it is organized. It uses the conditional operator in an always block to assign q = a^b (XOR) when enabled, else q=0.

  14. Conditionals (GNU make)

    A conditional directive causes part of a makefile to be obeyed or ignored depending on the values of variables. Conditionals can compare the value of one variable to another, or the value of a variable to a constant string. Conditionals control what make actually "sees" in the makefile, so they cannot be used to control recipes at the time of execution.

  15. Conditional Statements in Python

    Conditional statements in Python are used to execute a specific block of code based on the truth value of a condition. The most common conditional statements in Python are if, elif, and else. These allow the program to react differently depending on whether a condition (or a series of conditions) is true or false.

  16. Best way to do conditional assignment in python

    Easy! For more conditional code: a = b if b else val. For your code: a = get_something() if get_something() else val. With that you can do complex conditions like this: a = get_something() if get_something()/2!=0 else val. answered Jul 15, 2011 at 9:12. Phyo Arkar Lwin.

  17. Verilog Conditional Operator

    Nested Conditional Operators There are examples in which it might be useful to combine two or more conditional operators in a single assignment. Consider the truth table below. The truth table shows a 2-input truth table. You need to know the value of both r_Sel [1] and r_Sel [0] to determine the value of the output w_Out.

  18. Immediate Assignment (GNU make)

    First, after assignment the variable is a normal recursive variable; when you append to it with ' += ' the value on the right-hand side is not expanded immediately. If you prefer the ' += ' operator to expand the right-hand side immediately you should use the ':= ' / '::= ' assignment instead. Second, these variables are ...

  19. Copy of U4 L8 Assignment

    Purpose: The purpose of the assignment is to make an app using conditionals that include

  20. python

    One line if-condition-assignment Asked 12 years, 10 months ago Modified 1 year, 6 months ago Viewed 506k times

  21. Marlins Designate Jonathan Bermudez For Assignment

    The Marlins designated left-handed reliever Jonathan Bermudez for assignment Thursday amid a series of moves. Read more at MLB Trade Rumors.

  22. Python conditional assignment operator

    There is conditional assignment in Python 2.5 and later - the syntax is not very obvious hence it's easy to miss. Here's how you do it: x = true_value if condition else false_value