Is there a Python equivalent of the C# null-coalescing operator?

Is there a Python equivalent of the C# null-coalescing operator?

other = s or some default value

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C♯s null-coalescing operator, but keep in mind:

42    or something    # returns 42
0     or something    # returns something
None  or something    # returns something
False or something    # returns something
    or something    # returns something

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

In some languages this behavior is referred to as the Elvis operator.


other = s if s is not None else default value

Otherwise, s = False will become default value, which may not be what was intended.

If you want to make this shorter, try:

def notNone(s,d):
    if s is None:
        return d
        return s

other = notNone(s, default value)

Is there a Python equivalent of the C# null-coalescing operator?

Heres a function that will return the first argument that isnt None:

def coalesce(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

# Prints banana
print coalesce(None, banana, phone, None)

reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:

def coalesce(*arg):
  for el in arg:
    if el is not None:
      return el
  return None

Related Posts

What is sys.maxint in Python 3?

What is sys.maxint in Python 3?

The sys.maxint constant was removed, since there is no longer a limit
to the value of integers. However, sys.maxsize can be used as an
integer larger than any practical list or string index. It conforms to
the implementation’s “natural” integer size and is typically the same
as sys.maxint in previous releases on the same platform (assuming the
same build options).

As pointed out by others, Python 3s int does not have a maximum size, but if you just need something thats guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float(inf).

Note: as per elys comment, this may impact the efficiency of your code, so it may not be the best solution.

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:


Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:


Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.

Related Posts

visibility – How to hide a turtle icon/pointer in Python

visibility – How to hide a turtle icon/pointer in Python

The documentation has a section on Visibility:

Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably.

>>> turtle.hideturtle()

Also, you can un-hide the turtle:

Make the turtle visible.

>>> turtle.showturtle()

You can also query its visibilty:

Return True if the Turtle is shown, False if it’s hidden.

>>> turtle.hideturtle()
>>> turtle.isvisible()
>>> turtle.showturtle()
>>> turtle.isvisible()

One more practical method that the other answer failed to address is to set the visible keyword argument to False when defining the Turtle object:

import turtle

my_turtle = turtle.Turtle(visible=False)

Of course, that is for when you want the Turtle to be invisible from the very beginning of the program.

When you define a Turtle object without setting visible to False, there will always be a lightning short moment where the turtle is still visible:

import turtle

my_turtle = turtle.Turtle()
# The Turtle may be visible before the program reaches the line under, depending on the speed of your computer 

With the visible keyword argument set to False, you can always call my_turtle.showturtle() and my_turtle.hideturtle() in your code where ever the Turtle needs to be visible and hidden again.

Here are all the default turtle settings that you can customize (the settings of interest here are the ones commented with the # RawTurtle):

_CFG = {width : 0.5,               # Screen
        height : 0.75,
        canvwidth : 400,
        canvheight: 300,
        leftright: None,
        topbottom: None,
        mode: standard,          # TurtleScreen
        colormode: 1.0,
        delay: 10,
        undobuffersize: 1000,      # RawTurtle
        shape: classic,
        pencolor : black,
        fillcolor : black,
        resizemode : noresize,
        visible : True,
        language: english,        # docstrings
        exampleturtle: turtle,
        examplescreen: screen,
        title: Python Turtle Graphics,
        using_IDLE: False

Update: I just noticed that cdlanes comment on the other answer pointed out this method, but comments are temporary.

visibility – How to hide a turtle icon/pointer in Python

Related Posts

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Check out enigmas answer

wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

I think that method is depreciated,
In the newer version of openpyxl library
you can use this method to get the Row Count and Column count

#to get the row count
#to get the column count

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Related Posts

python – How to convert _io.TextIOWrapper to string?

python – How to convert _io.TextIOWrapper to string?

You need to use the output of

string =

I think your confusion is that f will be turned into a string just by calling its method .read(), but thats not the case. I dont think its even possible for builtins to do that.

For reference, _io.TextIOWrapper is the class of an open text file. See the documentation for io.TextIOWrapper.

By the way, best practice is to use a with-statement for opening files:

with open(document.txt, r, encoding=utf-8-sig) as f:
    string =

Its not a super elegant solution but it works for me

def extractPath(innie):
    iggy = str(innie)

    getridofme =<_io.TextIOWrapper name=
    getridofmetoo = mode=r encoding=UTF-8>

    iggy = iggy.replace(getridofme, )
    iggy = iggy.replace(getridofmetoo, )


    return iggy

python – How to convert _io.TextIOWrapper to string?

Related Posts

UserWarning: Could not import the lzma module. Your installed Python is incomplete

UserWarning: Could not import the lzma module. Your installed Python is incomplete

If you compile Python from source, you must have the lzma-dev package installed, or it will not be built into python.

For ubuntu: sudo apt-get install liblzma-dev

For centos: yum install -y xz-devel

Then configure && make && make install

I used other good answers from here and didnt solve the problem (Ubuntu 18.04, Python3.8), still get this warning.
Actually there is one more package is needed to be installed to solve the problem:

sudo apt-get install lzma

So the whole pipeline (run in the python source code folder):

sudo apt-get install liblzma-dev
sudo apt-get install lzma
./configure --enable-optimizations
sudo make
sudo make altinstall

UserWarning: Could not import the lzma module. Your installed Python is incomplete

On MacOS and pyenv (, I was able to have this warning go away by having xz installed with homebrew. Using version python 3.6.9 as an example

brew install xz && pyenv install 3.6.9

To use installed python, one needs to add this into .bash_profile

eval $(pyenv init -)

and start using it by running

pyenv global 3.6.9

Related Posts

tensorflow.python.framework.ops.EagerTensor object has no attribute _in_graph_mode

tensorflow.python.framework.ops.EagerTensor object has no attribute _in_graph_mode

The reason for the bug is that the tf.keras optimizers apply gradients to variable objects (of type tf.Variable), while you are trying to apply gradients to tensors (of type tf.Tensor). Tensor objects are not mutable in TensorFlow, thus the optimizer cannot apply gradients to it.

You should initialize the variable img as a tf.Variable. This is how your code should be:

# NOTE: The original image is lost here. If this is not desired, then you can
# rename the variable to something like img_var.
img = tf.Variable(img)
opt = tf.optimizers.Adam(learning_rate=lr, decay = 1e-6)

for _ in range(epoch):
    with tf.GradientTape() as tape:
        y = model(img.value())[:, :, :, filter]
        loss = -tf.math.reduce_mean(y)

    grads = tape.gradient(loss, img)
    opt.apply_gradients(zip([grads], [img]))

Also, it is recommended to calculate the gradients outside the tapes context. This is because keeping it in will lead to the tape tracking the gradient calculation itself, leading to higher memory usage. This is only desirable if you want to calculate higher-order gradients. Since you dont need those, I have kept them outside.

Note I have changed the line y = model(img)[:, :, :, filter] to y = model(img.value())[:, :, :, filter]. This is because tf.keras models need tensors as input, not variables (bug, or feature?).

Well although not directly related, but can be somewhat useful to understand what causes this type of errors at the first place.

This type of error occurs whenever we try to modify a constant tensor.

Simple example, which raise similar error below–

unchangeable_tensors = tf.constant([1,2,3])

A way to bypass the error is using tf.Variable() as shown below

changeable_tensors = tf.Variable([1,2,3])

tensorflow.python.framework.ops.EagerTensor object has no attribute _in_graph_mode

Related Posts

class – Python calling method without self

class – Python calling method without self

Also you can make methods in class static so no need for self. However, use this if you really need that.


class bla:
    def hello(self):

    def thing(self):
        print hello

static edition:

class bla:
    def hello():

    def thing():
        print hello

One reason is to refer to the method of that particular classs instance within which the code is be executed.

This example might help:

def hello():
    print global hello

class bla:
    def hello(self):

    def thing(self):
        print hello

b = bla()
>>> hello
global hello

You can think of it, for now, to be namespace resolution.

class – Python calling method without self

The short answer is because you can def thing(args) as a global function, or as a method of another class. Take this (horrible) example:

def thing(args):
    print Please dont do this.

class foo:
    def thing(self,args):
        print No, really. Dont ever do this.

class bar:
    def thing(self,args):
        print This is completely unrelated.

This is bad. Dont do this. But if you did, you could call thing(args) and something would happen. This can potentially be a good thing if you plan accordingly:

class Person:
    def bio(self):
        print Im a person!

class Student(Person):
    def bio(self):
        print Im studying %s % self.major

The above code makes it so that if you create an object of Student class and call bio, itll do all the stuff that would have happened if it was of Person class that had its own bio called and itll do its own thing afterwards.

This gets into inheritance and some other stuff you might not have seen yet, but look forward to it.

Related Posts

ImportError: cannot import name abs from tensorflow.python.keras._impl.keras.backend

ImportError: cannot import name abs from tensorflow.python.keras._impl.keras.backend


I was able to resolve this issue by removing all the tensorFlow and keras python3 packages from dist-packages dir itself , uninstalling using pip3 and then again installing tensorflow==1.8.0
tensorflow-gpu==1.8.0 , Keras==2.2.4

( The Potential reason which caused this specific erro was python referring multiple tensoflow-gpu,keras version packages files in dis-packages dir. Although installing a specific tensoflow-gpu,keras version via pip3 should ideally remove previous existing versions. But In my case that didnt occurred.)


  1. Locate tensorflow , keras packages in dist-packages dir using $ locate --basename tensorflow command (provided you are using Ubuntu). In my case it is

$ locate –basename tensorflow

outputs –



$ locate –basename keras


  1. Now that you are aware of the desired packages location. Simply remove the tensorflow and keras dirs and uninstall packages using below commands

Removing dirs

sudo rm -R /usr/local/lib/python3.5/dist-packages/tensorflow/
sudo rm -R /usr/share/nginx/html/projects/python/machine-learning/objectDetection/models-master/research/syntaxnet/tensorflow

sudo rm -R /usr/local/lib/python3.5/dist-packages/keras/
sudo rm -R /usr/share/nginx/html/projects/python/Playground/lambda/testkeras/keras

Uninstall using pip3

sudo pip3 uninstall tensorflow
sudo pip3 uninstall tensorflow-gpu
sudo pip3 uninstall keras
  1. Again Installing tensorflow, tensorflow-gpu ,keras

    sudo pip3 install tensorflow==1.8.0
    sudo pip3 install tensorflow-gpu==1.8.0
    sudo pip3 install Keras==2.2.4

ImportError: cannot import name abs from tensorflow.python.keras._impl.keras.backend

Related Posts

Python Regex Error : nothing to repeat at position 0

Python Regex Error : nothing to repeat at position 0

This error message is not about position of arguments. Yes, in question above they are not in the right order, but this is only half of problem.

Ive got this problem once when i had something like this:**myword, /path/to/**myword) 

I wanted to get ** automatically so i did not wanted to write manually somewhere. For this cause there is re.escape() function. This is the right code:**myword), /path/to/**myword)

The problem here is that special character placed after the beginning of line.

You have your arguments for re.match backward: it should be

re.match(pattern, +how to block a website in edge)

Python Regex Error : nothing to repeat at position 0

Related Posts